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

@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);
    }

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值