Java 使用 Poi-tl word模板导出word

1.导入依赖

       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.7.3</version>
        </dependency>

2.新建一个word,制作导出模板

模板放入 resource/static/word/template文件夹下

3.编写工具类

工具类--WordExportServer.java

public class WordExportServer {


    /**
     * 导出word
     **/
    public static void export(WordExportData wordExportData) throws IOException {
        HttpServletResponse response=wordExportData.getResponse();
        OutputStream out = response.getOutputStream();;
        XWPFTemplate template =null;
        try{
            ClassPathResource classPathResource = new ClassPathResource(wordExportData.getTemplateDocPath());
            String resource = classPathResource.getURL().getPath();
            resource= PdfUtil1.handleFontPath(resource);
            //渲染表格
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder().bind(wordExportData.getTableDataField(), policy).build();
            template = XWPFTemplate.compile(resource, config).
                    render(wordExportData.getWordData());
            String fileName=getFileName(wordExportData);
            /** ===============生成word到设置浏览默认下载地址=============== **/
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

            template.write(out);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.flush();
            out.close();
            template.close();
        }
    }


    /**
     * 获取导出下载的word名称
     * @param wordExportData
     * @return java.lang.String
     **/
    public static String getFileName(WordExportData wordExportData){
        if(null !=wordExportData.getFileName()){
            return wordExportData.getFileName()+".docx";
        }
        return System.currentTimeMillis()+".docx";
    }

}

word数据包装类--WordExportData .java

@Data
public class WordExportData {

    /**
     * word模板路径(static/wordTemplate/dealerListDocTemplate.docx)
     **/
    private String templateDocPath;
    /**
     * word填充数据(key值与模板中的key值要保持一致)
     **/
    private Map<String,Object> wordData;
    /**
     * word表格数据key值
     **/
    private String tableDataField;
    /**
     * word导出后的文件名(不填则用当前时间代替)
     **/
    private String fileName;

    private HttpServletResponse response;
}

4.controller层调用

@RequestMapping("/printWord")
    public void printWord(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String[] ids=request.getParameter("ids").split(";");
        List<DealerDto> goodsDataList=goodsService.getDealerListByIds(ids);
        Map<String,Object> docData=new HashMap<>(3);
        docData.put("detailList",goodsDataList);
        docData.put("title",标题);
        docData.put("subTitle",副标题);
        WordExportData wordExportData=new WordExportData();
        wordExportData.setResponse(response);
        wordExportData.setTableDataField("detailList");
        wordExportData.setTemplateDocPath(DEALER_DOC_TEMPLATE_PATH);//副本存放路径
        wordExportData.setWordData(docData);
        WordExportServer.export(wordExportData);
    }

5.前端调用

                var ids = [];
                for (var index in checkData) {
                    ids.push(checkData[index].id);
                }
                var batchIds = ids.join(";");
                layer.confirm('确定下载选中的数据吗?', function (index) {
                    layer.close(index);
                    window.location.href =
                        '/goods/printWord?ids=' + batchIds;
                });

6.总结

优点:使用方法很简单,使用工具类的方法,方便复用于其他模块。使用者不需要关注word的复杂样式(可直接在模板中编辑好),只需要将数据包装好就行了。
缺点:在其他模块中使用,可能需要编辑新的模板word。

原文地址:https://www.cnblogs.com/xian-yu/p/14991153.html