/** * 根据指定的参数值、模板,生成 word 文档 * * Map中value值必须传入String型字符串; * key值和模板关键字或者变量命名规则都采用${},否则在解析模板时可能解析成“,”分割的变量发生解析错误,例如Tab101解析成“Tab,1”。 * * @param param * 需要替换的变量 * @param template * 模板 */ public static XWPFDocument generateWord(Map<String, Object> param, String template) { XWPFDocument doc = null; try { OPCPackage pack = POIXMLDocument.openPackage(template); doc = new XWPFDocument(pack); if (param != null && param.size() > 0) { // 处理段落 List<XWPFParagraph> paragraphList = doc.getParagraphs(); processParagraphs(paragraphList, param, doc); // 处理表格 Iterator<XWPFTable> it = doc.getTablesIterator(); while (it.hasNext()) { XWPFTable table = it.next(); List<XWPFTableRow> rows = table.getRows(); for (XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) { List<XWPFParagraph> paragraphListTable = cell .getParagraphs(); processParagraphs(paragraphListTable, param, doc); } } } } } catch (Exception e) { e.printStackTrace(); } return doc; } /** * 处理段落 * * @param paragraphList */ public static void processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param, XWPFDocument doc) { if (paragraphList != null && paragraphList.size() > 0) { for (XWPFParagraph paragraph : paragraphList) { List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); //System.out.println("----------"+text); if (text != null) { boolean isSetText = false; for (Entry<String, Object> entry : param.entrySet()) { String key = entry.getKey(); if (text.indexOf(key) != -1) { isSetText = true; Object value = entry.getValue(); if (value instanceof String) {// 文本替换 String v=value.toString(); text = text.replace("["+key+"]", v); //System.out.println("-----"+key+"----------"+value); }else { text = text.replace("["+key+"]",""); } } } if (isSetText) { run.setText(text, 0); } } } } } }
指定Word模板替换Word中的值
最新推荐文章于 2024-07-19 12:29:22 发布