Note that there are some explanatory texts on larger screens.

plurals
  1. POText replacement in WinWord doc using Apache POI
    text
    copied!<p>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.</p> <p>Range object specs: <a href="http://poi.apache.org/apidocs/org/apache/poi/hwpf/usermodel/Range.html#replaceText(java.lang.String" rel="nofollow noreferrer">http://poi.apache.org/apidocs/org/apache/poi/hwpf/usermodel/Range.html#replaceText(java.lang.String</a>, java.lang.String)</p> <p>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.</p> <p>Here's my code: (let's say a.doc just contains "caaaaaaake")</p> <pre><code> String inputFilename = "C:\\\a.doc"; String outputFilename = "C:\\b.doc"; POIFSFileSystem fs = null; FileInputStream fis = new FileInputStream(inputFilename); fs = new POIFSFileSystem(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(); </code></pre> <p>The code executes no problem, but it creates a broken word file. What can I do?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload