我需要替换WinWord文档中的某些文本。问题是,我使用replaceText函数对Range执行的任何文本替换都会创建一个损坏的WinWord文件,除非替换字符串和替换字符串的长度完全相同。我们将处理动态内容,所以这不会。使用Apache POI的WinWord文档中的文本替换
Range对象规格: http://poi.apache.org/apidocs/org/apache/poi/hwpf/usermodel/Range.html#replaceText(java.lang.String,java.lang.String中)
的replaceText函数有一个可选的第三个参数,一个int,以指定某种偏移。我想也许这可能是解决方案,但参数甚至无法处理负值,这使得替换很难或不可能,除非偏移量(replacement.length() - replaced.length())为正值。但是,我可能需要它是负面的。总之,文档中没有任何内容似乎意味着如果其他两个参数的长度不相等,则需要此偏移参数。
这里是我的代码: (假设a.doc只包含“caaaaaaake”)
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();
的代码执行没有问题,但它创建了一个断字的文件。 我能做什么?
的文件中用piiiie打开就好了。对不起,我不能建议POI修复,但如果你刚刚开始,你可以考虑其他免费选项,如[JODReports] [1]或[Docmosis] [2]。它们很方便,但需要更大的基础设施,因为您需要安装OpenOffice来帮助进行格式转换。 [1]:http://jodreports.sourceforge.net/ [2]:http://www.docmosis.com – 2010-08-03 02:56:40
谢谢,但不幸的是,我不能依赖OpenOffice。 Docmosis提到使用WinWord文件,但我需要一种文本替换方法,我无法在其API中找到它。 – Amalgovinus 2010-08-03 16:13:22
我有同样的问题。即使删除替换。我只是通过'HWPFDocument doc = new HWPFDocument(new POIFSFileSystem(new FileInputStream(path)));'然后编写'try(FileOutputStream out = new FileOutputStream(filePath))来读取输入文件{doc.write(out); }'。但它会生成损坏的文件。 – Bagdat 2016-10-05 05:00:07