java--word模板填充,不存本地,合并成一个word导出

需求:填充word模板,然后合并成一个word。

但是文件并不想保存在本地磁盘,直接再内存中处理完成,直接导出或者响应给前端下载;

pom如下:

        <!--poi-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.2</version>
        </dependency>
        <!--word文档处理-->
        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.12.2</version>
        </dependency>

注意事项:

pom中会对docx文件压缩(如果你得模板是在resources下得话),所以得事先设置,否则会报错

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <version>2.6</version>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <nonFilteredFileExtensions>
                        <nonFilteredFileExtension>docx</nonFilteredFileExtension>
                    </nonFilteredFileExtensions>
                </configuration>
            </plugin>

示例代码: 

 @Test
    public void tex21() throws Exception {
        
        List<ByteArrayInputStream> inputStreamList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            // 读取模板文件 路径是你的模板位置
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/问题审查报告.docx");
            
            //数据渲染
            XWPFTemplate template = XWPFTemplate.compile(resourceAsStream).render(
                    new HashMap<String, Object>() {{
                        put("A1", "Hi, poi-tl Word模板引擎" + System.currentTimeMillis());
                        put("A2", "Hi, poi-tl " + System.currentTimeMillis());
                        put("A3", "Hi, poi-tl Word" + System.currentTimeMillis());
                        put("A4", " Word模板引擎" + System.currentTimeMillis());
                        put("E1", "D:\\google\\L\\1.png");
                        put("E2", Pictures.ofUrl("https://picx.zhimg.com/v2-679d833cf193239e0d5ea51a3d6bb7cb_r.jpg?source=1def8aca")
                                .size(100, 100).create()
                        );
                    }});
            
            // 因为不想存到磁盘,再读取一边,所以直接在内存中处理完
            // 输出到ByteArrayOutputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();//二进制OutputStream
            template.writeAndClose(baos);//文档写入流
            ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());//new By

            // 写入到磁盘
//        FileOutputStream fileOutputStream = new FileOutputStream("D:\\word\\output" + System.currentTimeMillis() + ".docx");
//        template.writeAndClose(fileOutputStream);
            
            // 将所有填充好的模板收集成list
            inputStreamList.add(in);
        }
        // 合并文档方法
        tex22(inputStreamList);
    }

    //    @Test
    public void tex22(List<ByteArrayInputStream> inputStreamList) throws Exception {


        //导出的位置   
        String mergedFileName = "D:\\word\\hb" + System.currentTimeMillis() + ".docx";

//        List<File> inputFiles = new ArrayList<>();
//        inputFiles.add(new File("D:\\word\\output1713836542115.docx"));
//        inputFiles.add(new File("D:\\word\\output1713836639166.docx"));

        // 生成新文档
        FileOutputStream out = new FileOutputStream(mergedFileName);
        // 合并文档  main主文档
        NiceXWPFDocument main = new NiceXWPFDocument(Files.newInputStream(Paths.get("D:\\word\\2.docx")));
        // 遍历所有模板   
        // 也可以使用 list<file> 获取inputStream也行 但是需要存本地盘,很麻烦还得删,也不是所有的服务器都有权限       
        for (ByteArrayInputStream byteArrayInputStream : inputStreamList) {
            NiceXWPFDocument sub = new NiceXWPFDocument(byteArrayInputStream);
            // 合并文档  sub子文档
            main = main.merge(sub);
        }
        //写出到文件  或者响应成流传给前端下载,都行
        main.write(out);
        // 关闭流
        main.close();
        out.close();

    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当使用Poi-tl库根据Word模板填充内容生Word文档时,可以使用Poi-tl提供的模板语法来处理空值。以下是一个示例代码: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter; import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.HeaderFooterType; import org.apache.poi.xwpf.usermodel.IBodyElement; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class WordTemplateFiller { public static void main(String[] args) { try { // 加载Word模板文件 FileInputStream templateStream = new FileInputStream("template.docx"); XWPFDocument document = new XWPFDocument(templateStream); // 填充内容 Map<String, Object> placeholders = new HashMap<>(); placeholders.put("name", "John Doe"); placeholders.put("age", "30"); placeholders.put("address", ""); replacePlaceholders(document, placeholders); // 保填充后的文档 FileOutputStream outputStream = new FileOutputStream("filled_template.docx"); document.write(outputStream); outputStream.close(); System.out.println("Word文档生功!"); } catch (IOException e) { e.printStackTrace(); } } private static void replacePlaceholders(XWPFDocument document, Map<String, Object> placeholders) { for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { for (Map.Entry<String, Object> entry : placeholders.entrySet()) { String placeholder = "${" + entry.getKey() + "}"; if (text.contains(placeholder)) { Object value = entry.getValue(); if (value != null && !value.toString().isEmpty()) { text = text.replace(placeholder, value.toString()); } else { text = text.replace(placeholder, ""); // 替换为空字符串 } run.setText(text, 0); } } } } } } } ``` 在上述代码中,我们首先加载Word模板文件,然后定义了一个`placeholders`的映射,其中包含了要替换的占位符和对应的值。接下来,我们调用`replacePlaceholders`方法来替换文档中的占位符。 在`replacePlaceholders`方法中,我们遍历文档中的每个段落和文本运行,通过检查文本内容中是否包含占位符来确定是否需要替换。如果找到了匹配的占位符,则根据占位符对应的值来进行替换。如果值不为空且非空字符串,则将占位符替换为对应的值;如果值为空或空字符串,则将占位符替换为空字符串。 请注意,上述代码中使用的占位符格式为`${placeholder}`,你可以根据实际情况修改为其他格式。 以上是一个基本示例,你可以根据自己的需求进行修改和扩展。同时,需要确保在项目中添加了Poi-tl的依赖库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值