4.1.0
org.apache.poi poi${poi.version} org.apache.poi poi-ooxml${poi.version} org.apache.poi poi-scratchpad${poi.version} org.apache.poi poi-ooxml-schemas${poi.version} org.apache.poi poi-ooxml-schemas${poi.version}
public static void replaceInPara(XWPFParagraph para, Mapparams) { List 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 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);
public static void replaceInTable(XWPFDocument doc, Mapparams) { Iterator iterator = doc.getTablesIterator(); XWPFTable table; List rows; List cells; List 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); } } } } } public static Matcher matcher(String str) { Pattern pattern = Pattern.compile("\$\{(.+?)\}", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); return matcher; } public static void close(InputStream is) { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void close(OutputStream os) { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } }



