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

文章目录

  • 一、文章背景
  • 二、实现步骤
    • 2.1 需要的依赖
    • 2.2 创建模板
    • 2.3 书写java类
      • 2.3.1 模板目录
      • 2.3.2 Controller类
      • 2.3.2 工具类
    • 2.4 测试
      • 2.4.1 浏览器请求接口
      • 2.4.2 下载word
  • 三、注意事项
  • 四、其他导出word实现方式

一、文章背景

  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 工具类

/*** @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

在这里插入图片描述

三、注意事项

1、模板文件读取不到(容易出现错误-需及时更换文件读取方式)
2、list循环借鉴文章
https://blog.csdn.net/andy_67/article/details/124906812

四、其他导出word实现方式

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

借鉴文章

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/687423.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

去除Windows11广告,这款开源工具一键搞定!(汉化版)

文章目录 &#x1f4d6; 介绍 &#x1f4d6;&#x1f3e1; 演示环境 &#x1f3e1;&#x1f4d2; 工具介绍 &#x1f4d2;&#x1f388; 获取方式 &#x1f388;&#x1f4e2; 声明 &#x1f4d6; 介绍 &#x1f4d6; 你是否厌倦了在Windows 11中不断弹出的广告&#xff1f;是否…

Set接口

Set接口的介绍 Set接口基本介绍 无序&#xff08;添加和取出的顺序不一致&#xff09;&#xff0c;没有索引不允许重复元素&#xff0c;所以最多包含一个nullJDK API中Set接口的实现类&#xff1a;主要有HashSet&#xff1b;TreeSet Set接口的常用方法 和List 接口一样&am…

加速vivado编译工程

系统环境&#xff1a;windows11IDE环境&#xff1a;vivado2023.2工程&#xff1a;vivado自带的example project&#xff08;wave_gen&#xff09; Vivado支持多线程&#xff0c;可进一步缩短编译时间&#xff0c;这需要通过如下的Tcl脚本进行设置。综合阶段&#xff0c;Vivado可…

【ArcGISProSDK】condition属性

示例 通过caption属性可以看出esri_mapping_openProjectCondition的条件是一个工程被打开 condition的作用 由此可知示例中的Tab实在工程被打开才能使用&#xff0c;否则他禁用显示灰色&#xff0c;在未禁用的时候说明条件满足。 参考文档 insertCondition 元素 (arcgis.com…

金南瓜EAP库使用开发

前言 最近做了 一个半导体公司的上位机开发。厂商要求要支持EAP通讯。 先了解一下EAP是什么吧&#xff1f;百度资料 EAP&#xff08; Equipment Automation Program&#xff09;设备自动化处理&#xff0c;工厂实现设备自动化生产和管理。 1. 机台状态数据收集&#xff0c;包…

【C#】WebSoket 演示(使用websocket-sharp库)

Example 3服务器 Example1 客户端 示例3 此源代码片段包含了如何使用WebSocketSharp库来创建一个HTTP服务器&#xff0c;并提供WebSocket服务。 分析整个代码&#xff0c;我们可以归纳出以下关键信息&#xff1a; 导入了一系列重要的命名空间&#xff0c;包括系统配置、加密库、…

MyBatis——使用MyBatis完成CRUD

CRUD&#xff1a;Create Retrieve Update Delete 1、insert <insert id"insertCar">insert into t_car(id,car_num,brand,guide_price,produce_time,car_type)values(null,1003,五菱宏光,30.0,2020-09-18,燃油车); </insert> 这样写显然是写死的&#…

HaDoop Hive

目录 1.VMware 的配置 2.JDK的部署 3.防火墙&#xff0c;SElinux&#xff0c;时间同步设置 4.云平台 5.阿里云 6.UCloud 7.Hadoop理论 7.1 Hadoop理论 7.2 VMware Hadoop实践 7.3集群部署常见问题解决 7.4 云服务器上 Hadoop实践 7.5 HDFS 的 shell 7.6…

TVM简介

TVM FGPA,CPU, GPU 1.什么是TVM&#xff1f; 是一个支持GPU&#xff0c;CPU&#xff0c;FPGA指令生成的开源编译器框架 2.特点 基于图和算符结构来优化指令生成&#xff0c;最大化硬件执行效率。其中使用了很多方法 来改善硬件执行速度&#xff0c;包括算符融合、数据规划…

指代消解类方法梳理

概念&#xff1a; MLM&#xff1a;带遮罩的语言模型 NSP&#xff1a;单句预测&#xff0c;任务包括两个输入序列 SBO&#xff1a;分词边界目标 1.spanBERT&#xff0c;2019 spanBERT是对bert从分词到文本跨度的优化&#xff0c;主要有两方面的优化&#xff1a;&#xff08…

Llama 3 是怎么回事?Arena 数据分析

4 月 18 日,Meta 发布了他们最新的开放权重大型语言模型 Llama 3。从那时起,Llama 3-70B 就在 English Chatbot Arena 排行榜上迅速上升,拥有超过 50,000 次对战。Meta 的这一非凡成就对开源社区来说是个好消息。在这篇博文中,我们旨在深入探讨为什么用户将 Llama 3-70b 与 GPT…

代码随想录——二叉树的层序遍历Ⅱ(Leetcode107)

题目链接 层序遍历&#xff08;队列&#xff09; /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val val; }* TreeNode(int val, Tre…