【发布时间】:2014-01-15 00:43:57
【问题描述】:
我需要替换 WinWord 文档中的某些文本。问题是,我在 Range 上使用 replaceText 函数进行的任何文本替换都会创建损坏的 WinWord 文件,除非替换字符串和替换字符串的长度完全相同。我们将处理动态内容,因此不会这样做。
范围对象规格: 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();
代码执行没有问题,但它会创建一个损坏的单词文件。 我能做什么?
【问题讨论】:
-
抱歉,我无法建议 POI 修复,但如果您刚刚开始,您可以考虑其他免费选项,例如 [JODReports][1] 或 [Docmosis][2]。它们很方便,但对基础架构的要求更大,因为您需要在某处安装 OpenOffice 以帮助进行格式转换。 [1]:jodreports.sourceforge.net [2]:docmosis.com
-
谢谢,但不幸的是,我不能依赖 OpenOffice。 Docmosis 提到了使用 WinWord 文件,但我需要一个文本替换方法,我在它的 API 中找不到。
-
我也有同样的问题。甚至删除替换。我只是通过
HWPFDocument doc = new HWPFDocument(new POIFSFileSystem(new FileInputStream(path)));读取输入文件,然后写入try (FileOutputStream out = new FileOutputStream(filePath)) { doc.write(out); }。但它会生成损坏的文件。
标签: java ms-word apache-poi