poi根据Word模板导出Word文件,Word模板

从别人那里看的,结果后来发版到服务器导出时报错,访问不到模板路径位置,后来改成了。这里我自己整理一下

重点:解决 访问不到Word模板路径

//word模板文件流 这种方法不会在linux上或者jar启动失效
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/template/test2.docx");

1.引入依赖,添加到pom.xml文件

        <!-- word导出 -->
        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.7.3</version>
        </dependency>
        <!--  上面需要的依赖-->
        <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>

2.新建一个controller用于测试,下图是我的模板路径(声明一下我这里是springboot项目)  src/main/resources/static/template/test2.docx

@RequestMapping("/auth/exportWord/")
@RestController
public class ExportWordController {

    /**
     * 导出word --- poi-tl(包含动态表格)
     */
    @RequestMapping("/exportDataWord3")
    public void exportDataWord3(HttpServletResponse response) throws IOException {
        try {
            //组装动态表格列表数据
            List<Map<String,Object>> detailList = new ArrayList<Map<String,Object>>();
            for (int i = 0; i < 5; i++) {
                Map<String,Object> detailMap = new HashMap<String, Object>();
                detailMap.put("procName", "总装" + i + "工序");//工序
                detailMap.put("reportName", "隔壁老王" + i);//装配人员
                detailMap.put("materialName","压缩机组件" + i);
                detailMap.put("number","20210817" + i);
                detailMap.put("installNum",i + "台");
                detailList.add(detailMap);
            }
            //word模板文件流 这种方法不会在linux上或者jar启动失效
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/template/test2.docx");
            //渲染表格
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder().bind("detailList", policy).build();
            XWPFTemplate template = XWPFTemplate.compile( inputStream, config).render(
                    new HashMap<String, Object>() {{
                        put("detailList", detailList);
                        put("predefine2", "AR系列");
                        put("no","20210803001");
                        put("spec","AR-5-N");
                        put("planStartDate", "2021-9-10 16:11:00");
                        put("customerName","非洲私立医院");
                        put("salesorderNo","ATCL21-023");
                        put("test1","10088200");
                        put("test2","隔壁老王");
                        put("test3","隔壁老王");
                    }}
            );
            //生成文件名
            String fileName = new Date().getTime() + ".docx";//文件名  带后缀
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名,解决中文乱码问题
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition",
                    "attachment; filename=\"" + new String("记录跟踪单".getBytes("gbk"),"iso8859-1") + fileName + "\"");
            OutputStream out = response.getOutputStream();
            template.write(out);
            out.flush();
            out.close();
            template.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

3.Word模板样式:

 4.导出结果:

                                        AR系列氧气机生产记录跟踪单

SAET-7.5-027/C                                                                                  N0.:20210803001

产品型号

AR-5-N

计划生产日期

2021-9-10 16:11:00

客    户

非洲私立医院

订单号

ATCL21-023

工 序

装配人员

主要材料名称

批号/编号

安装数量

总装0工序

隔壁老王0

压缩机组件0

202108170

0台

总装1工序

隔壁老王1

压缩机组件1

202108171

1台

总装2工序

隔壁老王2

压缩机组件2

202108172

2台

总装3工序

隔壁老王3

压缩机组件3

202108173

3台

总装4工序

隔壁老王4

压缩机组件4

202108174

4台

颜    色

其    它

整机编号:10088200                                          验证:隔壁老王     批准:隔壁老王

你可以使用 Java 的 Apache POI 库来操作 Word 文档。具体步骤如下: 1. 创建一个空的 Word 文档,并打开它。 ``` XWPFDocument document = new XWPFDocument(); ``` 2. 读取 Word 模板文件,并将其转换为 XWPFDocument 对象。 ``` InputStream in = new FileInputStream(new File("template.docx")); XWPFDocument template = new XWPFDocument(in); ``` 3. 使用模板文件填充数据,可以使用类似 Freemarker 的模板引擎来实现。例如,使用占位符 `${name}` 来代表姓名,然后将其替换为实际的姓名。 ``` String name = "张三"; for (XWPFParagraph p : template.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null && text.contains("${name}")) { text = text.replace("${name}", name); r.setText(text, 0); } } } } ``` 4. 将填充好数据的模板文件内容复制到空的 Word 文档中。 ``` for (IBodyElement e : template.getBodyElements()) { document.createParagraph().createRun().setText(e.getParagraphText()); } ``` 5. 将文档保存到本地文件。 ``` FileOutputStream out = new FileOutputStream(new File("output.docx")); document.write(out); out.close(); ``` 以上就是使用 Java 的 Apache POI 库根据模板导出 Word 的基本步骤。需要注意的是,模板文件中可能包含多个段落和表格,需要分别处理。另外,如果需要插入图片等其他内容,也可以使用 POI 库提供的相应类来实现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值