Java 替换word文档文字

2021-06-21 00:00:00 文档 文字 替换

最近项目中需要在word文档中指定位置动态添加文字,记录下项目中的实现方式

  1. 添加依赖的lib
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>3.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.8</version>
        </dependency>
  1. 在word文档中添加标识位
    《Java 替换word文档文字》
  2. 代码
public class WordTest { 

    public static void main(String[] args) throws Exception { 
        Map<String, String> map = new HashMap<>();
        map.put("$name", "1231");
        XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage("E:\\新建文件夹\\demo.docx"));
        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) { 
            XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
            List<XWPFRun> runs = paragraph.getRuns();
            for (int i = 0; i < runs.size(); i++) { 
                String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition()).trim();
                for (Map.Entry<String, String> entry : map.entrySet()) { 
                    if (oneparaString.equals(entry.getKey())) { 
                        oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
                    }

                }
                runs.get(i).setText(oneparaString, 0);
            }
        }
        FileOutputStream outStream = null;
        outStream = new FileOutputStream("E:\\新建文件夹\\test1.docx");
        document.write(outStream);
        outStream.close();

    }
}
  1. 效果
    《Java 替换word文档文字》
    《Java 替换word文档文字》
    原文作者:无法无天过路客
    原文地址: https://blog.csdn.net/yangbaggio/article/details/106436341
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章