1.需求描述
用户提供word文件,需要开发功能,在word限定的位置,后台更新用户一些操作后输入的值
实现思路:通过在word待插入位置预置书签占位(这种方式不影响用户直观视觉体验),然后用poi去读取并替换这些书签,改为真实值
本案例用的文档
2.最终效果展示
3.代码实现
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.impl.store.DomImpl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* 使用 POI 读取 doc / docx 中的书签、替换书签内容
* <!-- word加标签 start-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.0</version>
</dependency>
<!-- word加标签 end-->
*/
public class TestWordBookmarkToString{
/**
* 测试函数.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
final LocalTime time = LocalTime.now();
// 替换 docx 文件中的 bookmark 内容
final String attr = ".docx";
final String inPath = "F:\\BiaoQian" + attr;
final String outPath = "F:\\BiaoQianNew" + time.format(DateTimeFormatter.ofPattern("HH时mm分ss秒SSS")) + attr;
final InputStream inputStream = Files.newInputStream(Paths.