一、要用到的jar包
我已上传了相关的jar包,需要的可以通过以下链接直接下载:
https://download.csdn.net/download/qq_27387133/88558034
具体jar包截图:
二、实现的代码
注意:文件要用docx格式!!!
word变量替换的方法(replaceWord):
/** * @Description: TODO word替换变量的方法* @author: zgx * @date: 2023年11月20日 下午3:03:42* @param srcPath 模板路径* @param destPath 输出路径* @param map 替换的变量值集合* @return * @return: boolean */public static boolean replaceWord(String srcPath,String destPath, HashMap<String, Object> map) {try {// 替换的的关键字存放到Set集合中Set<String> set = map.keySet();// 读取模板文档XWPFDocument document = new XWPFDocument(new FileInputStream(srcPath));/*** 替换段落中的指定文字*/// 读取文档中的段落,回车符为一个段落。// 同一个段落里面会被“:”等符号隔开为多个对象Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();while (itPara.hasNext()) {// 获取文档中当前的段落文字信息XWPFParagraph paragraph = (XWPFParagraph) itPara.next();List<XWPFRun> run = paragraph.getRuns();// 遍历段落文字对象for (int i = 0; i < run.size(); i++) {// 获取段落对象if (run.get(i) == null) { //段落为空跳过continue;}String sectionItem = run.get(i).getText(run.get(i).getTextPosition()); //段落内容// 遍历自定义表单关键字,替换Word文档中的内容Iterator<String> iterator = set.iterator();while (iterator.hasNext()) {// 当前关键字String key = iterator.next();// 替换内容sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));}run.get(i).setText(sectionItem, 0);}}/*** 替换表格中的指定文字*///获取文档中所有的表格,每个表格是一个元素Iterator<XWPFTable> itTable = document.getTablesIterator();while (itTable.hasNext()) {XWPFTable table = (XWPFTable) itTable.next(); //获取表格内容int count = table.getNumberOfRows(); //表格的行数//遍历表格行的对象for (int i = 0; i < count; i++) {XWPFTableRow row = table.getRow(i); //表格每行的内容List<XWPFTableCell> cells = row.getTableCells(); //每个单元格的内容//遍历表格的每行单元格对象for (int j = 0; j < cells.size(); j++) {XWPFTableCell cell = cells.get(j); //获取每个单元格的内容List<XWPFParagraph> paragraphs = cell.getParagraphs(); //获取单元格里所有的段落for (XWPFParagraph paragraph : paragraphs) {//获取段落的内容List<XWPFRun> run = paragraph.getRuns();// 遍历段落文字对象for (int o = 0; o < run.size(); o++) {// 获取段落对象if (run.get(o) == null || run.get(o).equals("")) {continue;}String sectionItem = run.get(o).getText(run.get(o).getTextPosition()); //获取段落内容if (sectionItem == null || sectionItem.equals("")) { //段落为空跳过continue;}//遍历自定义表单关键字,替换Word文档中表格单元格的内容for (String key : map.keySet()) {// 替换内容sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));run.get(o).setText(sectionItem, 0);}}}}}}
// 设置word不可编辑
// document.enforceFillingFormsProtection("123", HashAlgorithm.sha512);FileOutputStream outStream = null;outStream = new FileOutputStream(destPath);document.write(outStream);outStream.close();} catch (Exception e) {e.printStackTrace();}return true;}
具体地方调用replaceWord方法示例:
public void doReplaceWord(){String newPath = 路径+"你的新文件.docx";String oldPath = 路径+"你的模板文件.docx";HashMap<String, Object> resultMap = new HashMap<>();//简历名称resultMap.put("${resumeName}","我的简历");//创建时间resultMap.put("${createTime}","2023-10-10");//最后修改时间resultMap.put("${updateTime}","2023-11-10"); replaceWord(oldPath, newPath, resultMap);
}