Java动态导出word文档内容及图片

前言

最近公司在做一个工业柔性产线管控,项目中有一个需求要将工序中流程图及流程图中的子流程及工步相关信息导入到表格中(因为流程图下的子流程图有无及数量未知,所以最好的办法就是使用动态导入);因为以前更多接触的是excel的导入与导出,word还没接触过,刚好家人出现了黄码,就在家居家一天,顺便把相关需求写个demo;希望对有相关需求的朋友有帮助。
不废话,上代码

导入依赖

	  <!-- 处理word中的表格 -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>5.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>5.2.2</version>
		</dependency>
		<!-- 基于poi的word模板引擎 -->
		<dependency>
			<groupId>com.deepoove</groupId>
			<artifactId>poi-tl</artifactId>
			<version>1.12.0</version>
		</dependency>

初始化数据

/***
     * 初始化数据 封装数据
     * @return
     */
    public Map<String,Object> initWordData() {

        Map<String, Object> renderData = new HashMap<>();
        // 文本标题
        TextRenderData title = new TextRenderData("工序名称:...");
        renderData.put("title", title);

        // 文本内容
        StringBuilder contentData = new StringBuilder()
                .append("内容与大地112sada")
                .append(System.lineSeparator())
                .append("......");
        TextRenderData content = new TextRenderData(contentData.toString());
        renderData.put("content", content);

        //主流程图 图片可以本地的
        renderData .put("father", "D:\\27.jpg");

        Tables.TableBuilder tableBuilder = Tables.of(new String[][]{
                new String[]{"表头1", "表头2"},
                new String[]{"10", "11"},
                new String[]{"sadad", "da"}
        });
        //子流程图 网上随便找的
        Pictures.PictureBuilder childPic = Pictures.ofUrl("https://img12.360buyimg.com/n7/jfs/t1/198601/28/13395/148193/616ab0f7E31ac234b/9d504022a9069a2b.jpg");

        // child信息
        TextRenderData name = new TextRenderData("子流程");
        renderData.put("name1", name);
        renderData.put("table1",tableBuilder.border(BorderStyle.DEFAULT).create());
        renderData.put("pic1", childPic.create());

        return renderData;
    }

动态替换模板并导出

   /**
     * 根据实际情况导出模板
     */
    public void exportWord() {
        OutputStream os = null;
        XWPFTemplate template = null;
        try {
           Map<String, Object> renderData = initWordData();

           //编辑模板将模板动态化
            Configure config = Configure.builder().bind("data", new DocumentRenderPolicy()).build();
            Map<String, Object> data = new HashMap<>();
            Documents.DocumentBuilder documentBuilder = Documents.of()
                    .addParagraph(Paragraphs.of("{{title}}").create())
                    .addParagraph(Paragraphs.of("{{content}}").create())
                    .addParagraph(Paragraphs.of("{{@father}}").create());

            for (int i = 1; i < 2; i++) {
                documentBuilder.addParagraph(Paragraphs.of("{{name"+i+"}}").create());
                documentBuilder.addParagraph(Paragraphs.of("{{#table"+i+"}}").create());
                documentBuilder.addParagraph(Paragraphs.of("{{@pic"+i+"}}").create());
            }
            DocumentRenderData document = documentBuilder.create();
            data.put("data", document);

            // 原始模板文件
            String templatePath = "D:\\simpleTemplate3.docx";
            InputStream is = new FileInputStream(new File(templatePath));

            // 根据配置编译  并渲染数据
            template = XWPFTemplate.compile(is,config).render(data);

            // 临时输出位置
            String outPath = "D:\\test32.docx";
            os = new FileOutputStream(new File(outPath));
            // 写出
            template.write(os);

            // 模板文件
            InputStream is2 = new FileInputStream(new File(outPath));
            // 渲染数据
            template = XWPFTemplate.compile(is2).render(renderData);
            // 最终输出位置
            String outPath2 = "D:\\test3.docx";
            os = new FileOutputStream(new File(outPath2));
            template.write(os);
            
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (template != null) {
                    template.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

测试

原始模板

在这里插入图片描述

临时模板

在这里插入图片描述
说明:{{var}}是文本标签;{{@var}}是图片标签;{{#var}}是表格标签

最终结果

在这里插入图片描述
需要说明的是目前 poi-tl 是最新的版本,需要poi的版本也较高需要更新到5.2.2,如果不需要临时模板这个也很好操作,最终输出为一个文件即可更改;最后希望对大家有帮助。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值