<poi.version>4.1.0</poi.version>
<!-- office 相关依赖jar包 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${poi.version}</version> </dependency>
/** * 替换段落里面的变量 * * @param para 要替换的段落 * @param params 参数 */ public static void replaceInPara(XWPFParagraph para, Map<String, String> params) { List<XWPFRun> runs; Matcher matcher; runs = para.getRuns(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); String runText = run.toString(); matcher = matcher(runText); for (Map.Entry<String, String> entry :params.entrySet()){ if (runText.equals(entry.getKey())){ runText=entry.getValue(); para.removeRun(i); para.insertNewRun(i).setText(runText); } } } }
只能修改docx文档,doc文件不支持
InputStream is =this.getClass().getClassLoader().getResourceAsStream("点检模板.docx" ); XWPFDocument doc = new XWPFDocument(is); //替换表格里面的变量 replaceInTable(doc, params); SimpleDateFormat formatter = new SimpleDateFormat("MM-dd"); Calendar calendar = Calendar.getInstance(); // get current instance of the calendar OutputStream os = new FileOutputStream("/"+sportEntiy.getVehicleId()+"-"+formatter.format(calendar.getTime())+".docx"); doc.write(os); close(os); close(is);
/** * 替换表格里面的变量 * * @param doc 要替换的文档 * @param params 参数 */ public static void replaceInTable(XWPFDocument doc, Map<String, String> params) { Iterator<XWPFTable> iterator = doc.getTablesIterator(); XWPFTable table; List<XWPFTableRow> rows; List<XWPFTableCell> cells; List<XWPFParagraph> paras; while (iterator.hasNext()) { table = iterator.next(); rows = table.getRows(); for (XWPFTableRow row : rows) { cells = row.getTableCells(); for (XWPFTableCell cell : cells) { paras = cell.getParagraphs(); for (XWPFParagraph para : paras) { replaceInPara(para, params); } } } } } /** * 正则匹配字符串 * * @param str * @return */ public static Matcher matcher(String str) { Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); return matcher; } /** * 关闭输入流 * * @param is */ public static void close(InputStream is) { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭输出流 * * @param os */ public static void close(OutputStream os) { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } }