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

文章介绍了如何在Java项目中利用ApachePOI库创建Word模板,通过WordExportServer工具类实现数据填充并自动导出Word文档。工具类处理了字体路径、表格渲染和文件命名,简化了数据导入和样式管理,但需注意模板的复用问题。
摘要由CSDN通过智能技术生成

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。

Java中,利用POI-TL(Apache POI的Template Library)模板引擎来处理Word文档并嵌入多重循环是很常见的需求。POI-TL提供了一种方便的方式来操作Microsoft Office文件,包括Word。下面是一个基本步骤,展示如何在模板中添加多重循环: 1. **引入依赖**: 首先,你需要在项目中引入`org.apache.poi.xwpf.usermodel`和`org.apache.poi.xwpf.template`库,这两个包包含处理Word模板和文档的功能。 2. **创建模板**: 使用`XWPFDocument.create()`方法创建一个新的Word模板文档,并加载预定义的模板文件。你可以从本地读取模板文件,或者直接作为字符串内容传递。 ```java XWPFDocument template = new XWPFDocument(new FileInputStream("template.docx")); ``` 3. **设置循环变量**: 设定一个或多个需要迭代的数据集合,比如List、Map等,用于填充模板中的循环部分。例如,假设你有一个学生列表: ```java List<Student> students = ...; // 学生对象列表 ``` 4. **遍历并插入数据**: 使用`XWPFParagraph`的`addRun()`方法,在模板的每个循环位置插入新的文本行。对于每个学生,你可以创建一个新的段落或者追加到现有段落。 ```java for (Student student : students) { XWPFParagraph para = template.addNewParagraph(); para.addRun().append(student.getName()); // 如果有其他信息,如成绩,可以继续添加到run中 } ``` 5. **替换占位符**: 在模板中可能有一些特殊的标签(通常是特殊字符或标记),表示需要动态填充的部分。使用`XWPFTextRun.replaceText()`方法将这些占位符替换为实际数据。 6. **保存结果**: 最后,将修改后的模板保存为一个新的Word文档。 ```java OutputStream outputStream = new FileOutputStream("output.docx"); template.write(outputStream); outputStream.close(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值