我在我的项目中使用了此示例。一切都很好,并且替换文本也很好,但是在我的输出文本文件中,应该是“居中”的,已经左对齐了。输入文件 - .doc,我觉得这是打破文件的格式,但我不知道问题是什么。如何解决这个问题?.doc文件中Apache-POI格式的文本问题
public class HWPFTest {
public static void main(String[] args){
String filePath = "F:\\Sample.doc";
POIFSFileSystem fs = null;
try {
fs = new POIFSFileSystem(new FileInputStream(filePath));
HWPFDocument doc = new HWPFDocument(fs);
doc = replaceText(doc, "$VAR", "MyValue1");
saveWord(filePath, doc);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
private static HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText){
Range r1 = doc.getRange();
for (int i = 0; i < r1.numSections(); ++i) {
Section s = r1.getSection(i);
for (int x = 0; x < s.numParagraphs(); x++) {
Paragraph p = s.getParagraph(x);
for (int z = 0; z < p.numCharacterRuns(); z++) {
CharacterRun run = p.getCharacterRun(z);
String text = run.text();
if(text.contains(findText)) {
run.replaceText(findText, replaceText);
}
}
}
}
return doc;
}
private static void saveWord(String filePath, HWPFDocument doc) throws FileNotFoundException, IOException{
FileOutputStream out = null;
try{
out = new FileOutputStream(filePath);
doc.write(out);
}
finally{
out.close();
}
}
}
我认为你可以使用docx文件 - 解压缩它,替换内容和回拉。我个人是为ods/odt文件做的。 – user1516873 2014-09-10 14:01:05
@ user1516873在POI项目获得了docx的牵引之前,我开发了一个使用POI项目的自定义docx相关部件。 DOCX格式中有一些微妙之处,简单的内容替换就会破坏事物。当然,在很多情况下它都可以工作,但是如果需要确保它可以工作,就需要付出额外的努力。 – 2014-09-11 20:13:23
@RainerSchwarze我会记下这件事,谢谢。对于OpenOffice格式,我没有这样的问题。 – user1516873 2014-09-12 07:12:15