项目中引用jar包
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.1.0</version>
</dependency>
文档样例
代码实现逻辑
public static void exportWord(String templatePath, String fileName,
HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<>();
map.put("故障编号", "JXH_002");
map.put("故障机号", "JH_092");
map.put("故障日期", "2024-08-04");
map.put("试验名称", "试验机名称1234");
map.put("故障类型", "故障类型123");
map.put("故障描述", "试验过程管理模块实现单试验管理,管理单个试验的试验名称、试验性质、试验周期及试验地点等属性,同时具备试验进度管理,能够添加不同试验阶段下的工作信息。");
map.put("故障原因", "试验过程管理模块实现单试验管理,管理单个试验的试验名称、试验性质、试验周期及试验地点等属性,同时具备试验进度管理,能够添加不同试验阶段下的工作信息。");
map.put("处理措施", "试验过程管理模块实现单试验管理,管理单个试验的试验名称、试验性质、试验周期及试验地点等属性,同时具备试验进度管理,能够添加不同试验阶段下的工作信息。");
map.put("后续改进建议", "试验过程管理模块实现单试验管理,管理单个试验的试验名称、试验性质、试验周期及试验地点等属性,同时具备试验进度管理,能够添加不同试验阶段下的工作信息。");
map.put("编写", "编写人");
map.put("校对", "校对人");
map.put("审核", "审核人");
Assert.notNull(templatePath, "模板路径不能为空");
Assert.notNull(fileName, "导出文件名不能为空");
Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
try {
XWPFDocument doc = null;
try {
doc = WordExportUtil.exportWord07(templatePath + "测试文档.docx", map);
} catch (Exception e) {
System.out.println("111");
throw new RuntimeException(e);
}
for (XWPFTable table : doc.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
addBreakInCell(cell);
}
}
}
File file = new File(templatePath + fileName);
FileOutputStream out = new FileOutputStream(file);
doc.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
private static void addBreakInCell(XWPFTableCell cell) {
if (cell.getText() != null && cell.getText().contains("\n")) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun run : p.getRuns()) {
if (run.getText(0) != null && run.getText(0).contains("\n")) {
String[] lines = run.getText(0).split("\n");
if (lines.length > 0) {
run.setText(lines[0], 0);
for (int i = 1; i < lines.length; i++) {
run.addBreak();
run.setText(lines[i]);
}
}
}
}
}
}
}