1,需要的jar: 2,替换docx 文档的文字、图片实例 * 注意事项: * word 中的替换的文字replaceStr 一定是从普通 txt 文本中粘贴过来的,这样才可以保证这些 replaceStr 的所有属性一致 * 才能保证这些 replaceStr 在同一个 XWPFRun 中。 public class WordTest2 { String templatePathX = "D:/temp/打印样本/poi/打印样本.docx"; String savePath = "D:/temp/打印样本/poi/打印样本-temp.docx"; //image String logoImagePath = "D:/temp/打印样本/forest_logo.png"; String IconImagePath = "D:/temp/打印样本/icon.jpg"; @Test public void testDocx() { try { WordDocxUtil wordDocxUtil=new WordDocxUtil(templatePathX); // ArrayList replaceEles =wordDocxUtil.getReplaceElements("\\$\\{[^{}]+\\}"); // for(String replaceEle:replaceEles){ // System.out.println(replaceEle); // } //替换文字 // Map map = new HashMap(); // map.put("${orderId}", "B123123"); // map.put("${boxName}", "王五"); // map.put("${course-1}", "语文"); // map.put("${score}", "85"); // wordDocxUtil.replaceText(map); //单个文字替换 // wordDocxUtil.replaceText("${course}", "语文"); //正则表达式文字替换 // wordDocxUtil.replaceTextByRegex("\\$\\{course-\\d\\}", "[-_-]"); //替换图片 // Map imageMap = new HashMap(); // imageMap.put("width", "50"); // imageMap.put("height", "50"); // imageMap.put("imageType", WordDocxUtil.getSuffix(logoImagePath)); // imageMap.put("content", WordDocxUtil.inputStream2ByteArray(new FileInputStream(logoImagePath), true)); // wordDocxUtil.replaceImage("${forestLogo}", imageMap); // // imageMap = new HashMap(); // imageMap.put("width", "50"); // imageMap.put("height", "50"); // imageMap.put("imageType", WordDocxUtil.getSuffix(IconImagePath)); // imageMap.put("content", WordDocxUtil.inputStream2ByteArray(new FileInputStream(IconImagePath), true)); // wordDocxUtil.replaceImage("${icon}", imageMap); //...