最近项目中需要在word文档中指定位置动态添加文字,记录下项目中的实现方式
1. 添加依赖的lib
<dependency> <groupId>org.a;/groupId> <artifactId>poi-excelant</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.a;/groupId> <artifactId>poi-scratchpad</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.a;/groupId> <artifactId>poi-ooxml</artifactId> <version>3.8</version> </dependency> <dependency> <groupId>org.a;/groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.8</version> </dependency>
2. 在word文档中添加标识位
3. 代码
public class WordTest { public static void main(String[] args) throws Exception { Map<String, String> map = new HashMap<>(); map.put("$name", "1231"); XWPFDocument document = new XWPFDocumen("E:\\新建文件夹\\demo.docx")); Iterator<XWPFParagraph> itPara = document.getParagraphsIterator(); while ()) { XWPFParagraph paragraph = (XWPFParagraph) i(); List<XWPFRun> runs = (); for (int i = 0; i < runs.size(); i++) { String oneparaString = runs.get(i).getTex(i).getTextPosition()).trim(); for ;String, String> entry : map.entrySet()) { if ())) { oneparaString = one(), en()); } } runs.get(i).setText(oneparaString, 0); } } FileOutputStream outStream = null; outStream = new FileOutputStream("E:\\新建文件夹\\;); document.write(outStream); ou(); } }
4. 效果