JAVA使用Apache POI动态导出Word文档

3 篇文章 0 订阅
2 篇文章 0 订阅

一、文章背景

  1. 基于Freemarker模版动态生成并导出word文档存在弊端,生成的word文档格式是xml类型(通过生成word文档然后点击另存为可以查看是xml类型);但我们当前的需求是对生成的word文档提供预览功能,在公司提供的接口中,如果word格式不是doc格式就不能正确展示数据;同时对于频繁修改模板,Freemarker不好维护等问题;于是就有了此篇文章。
  2. 调研市面上java导出word文档主流的方案以及弊端(借鉴以下文章):https://zhuanlan.zhihu.com/p/672525861
    在这里插入图片描述

二、实现步骤

2.1 普通篇-需要的依赖

<dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-base</artifactId>
     <version>4.4.0</version>
 </dependency>
 <dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-web</artifactId>
     <version>4.4.0</version>
 </dependency>
 <dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-annotation</artifactId>
     <version>4.4.0</version>
 </dependency>
 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi</artifactId>
     <version>4.1.1</version>
 </dependency>
 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
     <version>4.1.1</version>
 </dependency>

2.2 普通篇-创建模板

请添加图片描述

2.3 普通篇-书写java类

2.3.1 模板目录

在这里插入图片描述

2.3.2 Controller类

/**
 * @author henry
 * @version 1.0
 * @describe todo
 * @data 2024/5/10 09:44
 */
@Api("测试poi导出word")
@RestController
@RequestMapping("/poiExport")
@Slf4j
public class Controller {

    @ApiOperation("word模板下载")
    @GetMapping("/poiExport")
    public void exportWordByModel(HttpServletResponse response, String path){
        Map<String,Object> map = new HashMap<>();
        map.put("startTime","2023");
        map.put("endTime","2024");
        map.put("name","tom");
        map.put("age","23");
        map.put("sex","男");

        List<String> list = new ArrayList<>();
        list.add("2019就读A学校");
        list.add("2022就读B学校");
        list.add("2023上岸研究生");
        map.put("list",list);

        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setUrl(FileUtil.filePath("templates/cute.png").getPath());
        imageEntity.setWidth(80);
        imageEntity.setHeight(100);
        map.put("photo",imageEntity);

        FileUtil.exportWordByModel(response,map,"templates/word.docx","员工统计");
    }
}

2.3.2 Util类

/**
 * @author henry
 * @version 1.0
 * @describe todo
 * @data 2024/5/10 09:48
 */
public class FileUtil {
    /**
     * 根据模板导出Word
     * @param response
     * @param map
     * @param modelFileName
     * @param outFileName
     */
    public static void exportWordByModel(HttpServletResponse response, Map<String, Object> map, String modelFileName, String outFileName) {
        try {
            // 1.获取模板文件路径 - 重点
            //XWPFDocument word = WordExportUtil.exportWord07(modelFileName, map);有时候这种方式可以找到有时候找不到(不太清楚)
            String templatePath = filePath(modelFileName).getAbsolutePath();

            // 打印出模板文件的完整路径 - 校验路径是否存在
            File templateFile = new File(templatePath);
            if (templateFile.exists()) {
                System.out.println("模板文件存在: " + templateFile.getAbsolutePath());
            } else {
                System.out.println("模板文件不存在: " + templateFile.getAbsolutePath());
            }
            // 2.映射模板,替换数据
            XWPFDocument word = WordExportUtil.exportWord07(templatePath, map);
            // 3.设置返回参数的字符集
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/msexcel");
            response.setContentType("text/html; charset=UTF-8");
            // 4.设置响应类型为Word文档
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            // 5.中文文件名处理,否则报错
            String encodedFileName = URLEncoder.encode(outFileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".docx");
            // 6.将Word文档发送到浏览器
            word.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据文件名获取文件对象
     * @param modelFileName
     * @return
     */
    public static File filePath(String modelFileName) {
        // 获取类加载器
        ClassLoader classLoader = FileUtil.class.getClassLoader();
        // 尝试从类路径中加载资源
        URL resource = classLoader.getResource(modelFileName);
        return new File(resource.getFile());
    }
}

2.4 普通篇-测试

2.4.1 浏览器请求接口

在这里插入图片描述

2.4.2 下载word

在这里插入图片描述

2.5 额外篇-list集合遍历

2.5.1 模板

请添加图片描述

2.5.2 工具类

同生成基本word的工具类

2.5.3 Controller类

@ApiOperation("word模板下载(主要测试遍历)")
    @GetMapping("/poiExportList")
    public void exportWordByModelList(HttpServletResponse response, String path) throws Exception {
        Map<String, Object> map = new HashMap<>();

        Course chineseCourse = new Course("语文", 90.00);
        Course mathCourse = new Course("数学", 92.00);
        Course englistCourse = new Course("英语", 94.00);
        List<Course> courseList = new ArrayList<>();
        courseList.add(chineseCourse);
        courseList.add(mathCourse);
        courseList.add(englistCourse);
        map.put("courseList", courseList);

        FileUtil.exportWordByModel(response,map,"templates/wordList.docx","简介");
    }

2.5.4 生成的案例

请添加图片描述

2.6 额外篇-单元格中换行

2.6.1 模板

请添加图片描述

2.6.2 工具类

需要在单元格换行,只需要添加“//---------------------单元格换行----------------------”内的代码即可。然后根据索引获取对应的单元格

public class FileUtil {
    /**
     * 根据模板导出Word
     * @param response
     * @param map
     * @param modelFileName
     * @param outFileName
     */
    public static void exportWordByModel(HttpServletResponse response, Map<String, Object> map, String modelFileName, String outFileName) {
        try {
            // 1.获取模板文件路径 - 重点
//            XWPFDocument word = WordExportUtil.exportWord07(modelFileName, map);
            String templatePath = filePath(modelFileName).getAbsolutePath();

            // 打印出模板文件的完整路径 - 校验路径是否存在
            File templateFile = new File(templatePath);
            if (templateFile.exists()) {
                System.out.println("模板文件存在: " + templateFile.getAbsolutePath());
            } else {
                System.out.println("模板文件不存在: " + templateFile.getAbsolutePath());
            }
            // 2.映射模板,替换数据
            XWPFDocument word = WordExportUtil.exportWord07(templatePath, map);

            // ---------------------单元格换行----------------------
            // 获取表格
            XWPFTable table = word.getTables().get(0); // 假设表格是第一个
            // 根据行列索引获取单元格并设置样式
            int rowIndex = 0; // 假设单元格在第一行
            int colIndex = 1; // 假设单元格在第二列
            XWPFTableCell cell = table.getRow(rowIndex).getCell(colIndex);
            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            // 创建段落和运行实例
            XWPFParagraph para = cell.addParagraph();
            para.setWordWrapped(true); // 允许段落内的文本换行
            XWPFRun run = para.createRun();
            // 设置文本和换行符
            String text = (String) map.get("name");
            String[] lines = text.split("\n");
            run.setText(lines[0], 0);
            for (int i = 1; i < lines.length; i++) {
                run.addBreak(BreakType.TEXT_WRAPPING);
                run.setText(lines[i]);
            }
            // ---------------------单元格换行----------------------

            // 3.设置返回参数的字符集
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/msexcel");
            response.setContentType("text/html; charset=UTF-8");
            // 4.设置响应类型为Word文档
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            // 5.中文文件名处理,否则报错
            String encodedFileName = URLEncoder.encode(outFileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".docx");
            // 6.将Word文档发送到浏览器
            word.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据文件名获取文件对象
     * @param modelFileName
     * @return
     */
    public static File filePath(String modelFileName) {
        // 获取类加载器
        ClassLoader classLoader = FileUtil.class.getClassLoader();
        // 尝试从类路径中加载资源
        URL resource = classLoader.getResource(modelFileName);
        return new File(resource.getFile());
    }
}

2.6.3 Controller类

@ApiOperation("word模板下载(主要测试遍历)")
    @GetMapping("/poiExportList")
    public void exportWordByModelList(HttpServletResponse response, String path) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("name","lisi\nzhangsan");
        map.put("sex","男");
        map.put("nation","中国北京");
        map.put("age",12);

        FileUtil.exportWordByModel(response,map,"templates/wordList.docx","简介");
    }

2.6.4 生成的案例

请添加图片描述

三、注意事项

1、模板文件读取不到(容易出现错误-需及时更换文件读取方式)

四、其他导出word实现方式

JAVA利用Freemarker模版动态生成并导出word文档

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
POI-tl是一个基于Apache POIJava库,用于动态生成Word文档。它提供了一种简单而强大的方式来根据Word模板生成具有动态内容的文档。在使用POI-tl进行动态导出Word文档时,你需要在模板中定义需要替换的标记,并在代码中使用POI-tl的API来填充这些标记。 首先,你需要在项目中添加POI-tl的依赖。具体的依赖配置可以参考\[1\]中提供的文章。 然后,你需要准备一个Word模板,其中包含需要动态填充的内容。在模板中,你可以使用自定义的标记来标识需要替换的部分。这些标记可以是任意的字符串,但需要与代码中的标记保持一致。 接下来,在代码中,你可以使用POI-tl的API来加载模板并替换其中的标记。你可以使用POI-tl提供的方法来设置文本、图片、表格、页眉、页脚等内容。具体的使用方法可以参考\[3\]中提供的教程。 最后,你可以将生成的Word文档导出到文件或直接在浏览器中下载。你可以使用POI-tl提供的方法来实现导出功能。具体的导出方法可以参考\[2\]中提供的代码示例。 总结起来,使用POI-tl动态导出Word文档的步骤包括添加依赖、准备模板、替换标记、导出文档。希望这些信息对你有帮助。 #### 引用[.reference_title] - *1* *2* [SpringBoot+Poi-tl根据Word模板动态生成word(含动态行表格、合并单元格)](https://blog.csdn.net/qq_26383975/article/details/112238802)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [poi-tl导出word](https://blog.csdn.net/weixin_43580824/article/details/129549483)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值