根据word模板生成Word文档
Word模板:

[注]: {{}} 标识符内为需要动态生成的数据
Word生成后的文档:
工具类代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import cn.afterturn.easypoi.word.WordExportUtil; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.springframework.util.Assert; import java.io.File; import java.io.FileOutputStream; import java.util.Map; /** * word 工具类 */ public class WordUtils { /** * 生成word * @param templatePath 模板地址 * @param temDir 生成路径 * @param fileName 文件名 * @param params 数据 */ public static void createWord(String templatePath, String temDir, String fileName, Map<String,Object> params){ Assert.notNull(templatePath, "模板路径不能为空" ); Assert.notNull(temDir, "临时文件路径不能为空" ); Assert.notNull(fileName, "导出文件名不能为空" ); Assert.isTrue(fileName.endsWith( ".docx" ), "word导出请使用docx格式" ); if (!temDir.endsWith( "/" )) { temDir = temDir + File.separator; } File dir = new File(temDir); if (!dir.exists()) { dir.mkdirs(); } try { XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); String tmpPath = temDir + fileName; FileOutputStream fos = new FileOutputStream(tmpPath); doc.write(fos); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } } |
用到的jar包:
<!-- excel工具 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> </dependency> <!-- word --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.jfree</groupId> <artifactId>jcommon</artifactId> <version>1.0.24</version> </dependency> <dependency> <groupId>org.jfree</groupId> <artifactId>jfreechart</artifactId> <version>1.5.0</version> </dependency>
具体代码实例:
public String createWord(YjPostPlan postPlan) throws Exception { int i = 0; Map<String,Object> map = new HashMap<>(); // 预案名称 map.put("planName",postPlan.getPlanName()); // 岗位 map.put("postName",postPlan.getPostName()); // 预案种类 map.put("planType",postPlan.getPlanType()); // 预案等级 map.put("planLevelName",postPlan.getPlanLevel()); // 事故类型 map.put("eventType",postPlan.getEventType()); // 预案内容 map.put("planContentData",postPlan.getYjPostPlanContent()); // 在本地生成word,并返回路径地址 String templatePath = "D:\uploadPath\upload\wordyjPlan.docx"; // 应急预案模板 String fileName = postPlan.getPlanName() + UUID.randomUUID().toString().replace("-", "");// 文件名称 // 上传文件路径 String filePath = "D:\export\word";// 生成文件地址 String temDir = filePath + "/word/"; String fileNameAll = fileName + ".docx"; WordUtils.createWord(templatePath,temDir,fileNameAll,map); return temDir+fileNameAll; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下