package com.ruoyi.web.controller.tool; import org.apache.poi.xwpf.usermodel.*; import java.io.*; import java.util.*; public class WordTemplateProcessor { public static void fillTemplate(String templatePath, String outputPath,Map dataMap) { try { // 读取模板文件 FileInputStream fis = new FileInputStream(templatePath); XWPFDocument document = new XWPFDocument(fis); // 替换段落中的标记 for (XWPFParagraph paragraph : document.getParagraphs()) { replaceParagraph(paragraph, dataMap); } // 替换表格中的标记 for (XWPFTable table : document.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph paragraph : cell.getParagraphs()) { replaceParagraph(paragraph, dataMap); } } } } // 保存文件 FileOutputStream fos = new FileOutputStream(outputPath); document.write(fos); // 关闭资源 fos.close(); fis.close(); document.close(); System.out.println("模板填充完成!文件保存在: " + outputPath); } catch (Exception e) { e.printStackTrace(); } } private static void replaceParagraph(XWPFParagraph paragraph, Map dataMap) { String paragraphText = paragraph.getText(); for (Map.Entry entry : dataMap.entrySet()) { if (paragraphText.contains(entry.getKey())) { List runs = paragraph.getRuns(); TextSegment found = paragraph.searchText(entry.getKey(), new PositionInParagraph()); if (found != null) { // 替换文本 int beginRun = found.getBeginRun(); int endRun = found.getEndRun(); if (beginRun >= 0 && endRun >= 0) { // 删除原有runs for (int runPos = beginRun; runPos <= endRun; runPos++) { paragraph.removeRun(runPos); } // 创建新run XWPFRun newRun = paragraph.insertNewRun(beginRun); newRun.setText(entry.getValue()); // 复制原有格式 if (runs.size() > 0 && runs.get(0) != null) { XWPFRun styleRun = runs.get(0); newRun.setFontFamily(styleRun.getFontFamily()); newRun.setFontSize(styleRun.getFontSize()); newRun.setBold(styleRun.isBold()); newRun.setItalic(styleRun.isItalic()); } } } } } } public static void main(String[] args) { String templatePath = "/path/to/template.docx"; String outputPath = "/path/to/output.docx"; // fillTemplate(templatePath, outputPath, user); } }