java按word模板导出word文件

1.导入依赖

   <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.4.0</version>
        </dependency>
        <!--耦合了spring-mvc 基于AbstractView,极大的简化spring-mvc下的导出功能 -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.4.0</version>
        </dependency>
        <!-- 基础注解包,作用与实体对象上,拆分后方便maven多工程的依赖管理 -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.4.0</version>
        </dependency>

如果依赖报错的话,在后面加入以下配置

 <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>

2.核心代码分装

 private XWPFDocument getXwpfDocument(MsdsDto dto) throws Exception {
        //总数据Map
        Map<String, Object> data = new HashMap<>();
        data.put("mixtureName", dto.getMixtureName());
        data.put("hazardCategory", dto.getHazardCategory());
        data.put("signalWords", dto.getSignalWords());
        data.put("description", dto.getDescription());
        data.put("prevent", dto.getPrevent());
        data.put("reply", dto.getReply());
        data.put("deposit", dto.getDeposit());
        data.put("disposition", dto.getDisposition());
        data.put("ph", dto.getPh());
        data.put("cst", dto.getCst());
        List<String> pictograms = dto.getPictograms();
        //象形图地址
        if(CommonUtil.listNotEmpty(pictograms)) {
            if (pictograms.size() > 1) {
                // 创建三个子集合
                List<String> pictogram1 = new ArrayList<>();
                List<String> pictogram2 = new ArrayList<>();
                // 遍历原始集合并分配到子集合中
                int count = 0;
                for (int i = 0; i < pictograms.size() && count < 9; i++) {
                    if (count < 5) {
                        pictogram1.add(pictograms.get(i));
                    } else {
                        pictogram2.add(pictograms.get(i));
                    }
                    count++;
                }
                if(CommonUtil.listNotEmpty(pictogram1)){
                        ImageEntity  imageEntity1 = ExportUtils.getMergedImageEntityHorizontal(
                                80*pictogram1.size(), 80, pictogram1.toArray(new String[0]));
                    data.put("pictogram1", imageEntity1);//向右拼接多张图片
                }
                if(CommonUtil.listNotEmpty(pictogram2)){
                    ImageEntity   imageEntity2 = ExportUtils.getMergedImageEntityHorizontal(
                            80*pictogram2.size(), 80, pictogram2.toArray(new String[0]));
                    data.put("pictogram2", imageEntity2);
                }
            } else {
               ImageEntity imageEntity = ExportUtils.getImageFromUrl(dto.getPictograms().get(0), 80, 80);//一张图片
                data.put("pictogram1", imageEntity);
            }
        }
        //信息
        List<Map<String, Object>> components = new ArrayList<>();
        for (MsdsComponentDto componentDto : dto.getComponents()) {
            Map<String, Object> map = new HashMap<>();
            map.put("name",componentDto.getName());
            map.put("concentration",componentDto.getConcentration());
            map.put("cas",componentDto.getCas());
            components.add(map);
        }
        data.put("component", components);
        // 填充到模板
        // 使用 ClassPathResource 获取模板路径
        ClassPathResource templateResource = new ClassPathResource("templates/msds.docx");

        // 检查模板文件是否存在
        if (!templateResource.exists()) {
            throw new BusinessException("模板文件不存在");
        }

        // 使用模板路径生成 XWPFDocument
        XWPFDocument word = WordExportUtil.exportWord07(templateResource.getPath(), data);
        return word;
    }

3.设置返回请求头导出文件

 public void exportMSDSWord(HttpServletRequest req, HttpServletResponse response, MsdsDto dto) {
        try {
            XWPFDocument word = getXwpfDocument(dto);
            String fileName = URLEncoder.encode( dto.getMixtureName()+ "-msds.docx", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            ServletOutputStream outputStream = response.getOutputStream();
            word.write(outputStream);
            outputStream.close();
            word.close();
        }catch (Exception e){
            e.printStackTrace();
            // 处理错误
        }
    }

说明:可以导出图片、文字、列表。word模板里面单个字段填充用{{filed_name}},集合遍历使用{{fe:}} ,图片填充用{{filed_name}}。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值