1.解决方案思路
读入word文档,遍历段落和表格,替换表格中的模板文字,返回保存或返回给前端
2.依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
<!-- poi模板导入,主力包 -->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.1</version>
</dependency>
3.具体代码
注意读取文档时使用的是读取 .docx 格式文档的方法,.doc的读取方式不一样
3.1 写入要填充的模板和数据
@GetMapping("/downloadWord")
public void downloadWord(HttpServletResponse response) throws IOException {
// 要填充的数据
Map<String, String> data = new HashMap<>();
data.put("collegeName","2342");
data.put("isTrue","☑");
fillTemplate(response,data);
}
3.2 遍历段落和表格
private static void fillTemplate(HttpServletResponse response, Map<String, String> data) throws FileNotFoundException {
File file = ResourceUtils.getFile("本科教学课程总结表Out.docx");
String absolutePath = file.getAbsolutePath();
try (FileInputStream fis = new FileInputStream( ResourceUtils.getFile("classpath:本科教学课程总结表.docx"));
XWPFDocument document = new XWPFDocument(fis);
FileOutputStream fos = new FileOutputStream(absolutePath)) {
// 遍历每个段落
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (Map.Entry<String, String> entry : data.entrySet()) {
replacePlaceholder(paragraph, entry.getKey(), entry.getValue());
}
}
//遍历每个表格
for(XWPFTable table : document.getTables()){
for(XWPFTableRow row : table.getRows()){
for(XWPFTableCell cell : row.getTableCells()){
for(XWPFParagraph paragraph : cell.getParagraphs()){
for(Map.Entry<String, String> entry : data.entrySet()){
replacePlaceholder(paragraph, entry.getKey(), entry.getValue());
}
}
}
}
}
// 保存填充后的文档
document.write(fos);
System.out.println("生成的文档已保存到: " + absolutePath);
File outFile = new File(absolutePath);
InputStream is = new BufferedInputStream(Files.newInputStream(outFile.toPath()));
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/msword;charset=utf-8");
// 设置文件名
response.addHeader("Content-Disposition", "attachment;fileame=" + new String("课程总结报告".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
byte[] buffer = new byte[1024];
int len;
//从输入流中读取一定数量的字节,并将其存储在缓冲区字节数组中,读到末尾返回-1
while((len = is.read(buffer)) > 0){
System.out.println(len);
outputStream.write(buffer, 0, len);
}
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3.3 替换数据
private static void replacePlaceholder(XWPFParagraph paragraph, String placeholder, String value) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null && text.contains(placeholder )) {
text = text.replace( placeholder, value);
run.setText(text, 0);
}
}
}