开发者

Text replacement in WinWord doc using Apache POI

开发者 https://www.devze.com 2023-01-10 03:20 出处:网络
I need to replace certain text in a WinWord document. The problem is, any text replacement I do on a Range with the replaceText function creates a broken WinWord file unless the replacement and replac

I need to replace certain text in a WinWord document. The problem is, any text replacement I do on a Range with the replaceText function creates a broken WinWord file unless the replacement and replaced strings are both the exact same length. We will be dealing with dynamic content, so this will not do.

Range object specs: http://poi.apache.org/apidocs/org/apache/poi/hwpf/usermodel/Range.html#replaceText(java.lang.String, java.lang.String)

The replaceText function has an optional third parameter, an int, to specify some sort of offset. I thought maybe this could be the solution, but the param can't even handle a negative value, which makes it hard or impossible to do a replacement unless the offset (replacement.length() - replaced.length()) is positive. However, I may need it to be negative. Anyhow, nothing in the docs would seem to imply that this offset param is needed if the two other params aren't equal length.

Here's my code: (let's say a.doc just contains "caaaaaaake")

      String inputFilename = "C:\\\a.doc"; 

      String outputFilename = "C:\\b.doc";
      POIFSFileSystem fs = null;
      FileInputStream fis = new FileInputStream(inputFilename);
      fs = new POIFSFileSyste开发者_运维知识库m(fis);

      HWPFDocument doc = new HWPFDocument(fs);

      Range range = doc.getRange();
      range.replaceText("caaaaaaake", "piiiie");


      FileOutputStream fos = new FileOutputStream(outputFilename);
      doc.write(fos);

      fis.close();
      fos.close();

The code executes no problem, but it creates a broken word file. What can I do?


I believe that when you get to poi 3.8, this problem is addressed. When working with beta5, this code works for me. The word file generated can be opened just fine with piiiie in the file where your caaaaaaake used to be

0

精彩评论

暂无评论...
验证码 换一张
取 消