POI操作Word文档:对特定字符的替换

在网上找了挺多资料,帮助也很大,但是质量却都良萎不齐,把自己整理和使用的代码贴上来

public class DocWriter {  
  
    public static void searchAndReplace(String srcPath, String destPath,Map map) {  
        try {  
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(srcPath));  
            /** 
             * 替换段落中的指定文字 
             */  
            Iterator itPara = document.getParagraphsIterator();  
            while (itPara.hasNext()) {  
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();  
                Set set = map.keySet();  
                Iterator iterator = set.iterator();  
                while (iterator.hasNext()) {
                    String key = iterator.next();  
                    List run=paragraph.getRuns();  
                    for(int i=0;i	String text = run.get(i).getText(0);
                    	for (Entry e : map.entrySet()) {
                     	   if (text != null && text.contains(e.getKey())) {
                                text = text.replace(e.getKey(), e.getValue());
                                run.get(i).setText(text,0);
                              }
                        }  
                    }  
                }  
            } 
  
            /** 
             * 替换表格中的指定文字 
             */  
             Iterator 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 cells = row.getTableCells();  
                    for (XWPFTableCell cell : cells) {
                         for (XWPFParagraph p : cell.getParagraphs()) {
                             for (XWPFRun r : p.getRuns()) {
                               String text = r.getText(0);
                               for (Entry e : map.entrySet()) {
                                     if (text != null && text.contains(e.getKey())) {
                                       text = text.replace(e.getKey(), e.getValue());
                                       r.setText(text,0);
                                     }
                               }  
                             }
                          }


                    }  
                }  
            }  
            FileOutputStream outStream = null;  
            outStream = new FileOutputStream(destPath);  
            document.write(outStream);  
            outStream.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
    }  
  
    public static void main(String[] args) throws Exception {  
        Map map = new HashMap();  
        map.put("${title}", "POI word export");  
        map.put("${second}", "2");  
        map.put("${name}", "seawater");  
        map.put("${tel}", "0000-0000");  
        map.put("${remark}", "remark info");  
        String srcPath = "D:\\1.docx";  
        String destPath = "D:\\2.doc";  
        searchAndReplace(srcPath, destPath, map);  
    }  
}  

归根到底是使用循环遍历文档的方式进行替换,先遍历段落,在遍历行,判断是否包含要替换的文字。

如果文件目录没有创建的话会报错,可以先创建对应的文件目录再输出:

            File outDir =new File(dir);
            outDir.mkdirs();//创建目录
            FileOutputStream outStream = null;  
            outStream = new FileOutputStream(dir+fileName);//目录名+文件名  
            document.write(outStream);  
            outStream.close();  
如果word模板文件放在项目中,可以用 JavaPath.getWebRootPath();获取当前项目静态资源路径。

你可能感兴趣的:(后端)