2014-09-10 80 views
0

我在我的项目中使用了此示例。一切都很好,并且替换文本也很好,但是在我的输出文本文件中,应该是“居中”的,已经左对齐了。输入文件 - .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(); 
     } 
    } 
} 
+0

我认为你可以使用docx文件 - 解压缩它,替换内容和回拉。我个人是为ods/odt文件做的。 – user1516873 2014-09-10 14:01:05

+1

@ user1516873在POI项目获得了docx的牵引之前,我开发了一个使用POI项目的自定义docx相关部件。 DOCX格式中有一些微妙之处,简单的内容替换就会破坏事物。当然,在很多情况下它都可以工作,但是如果需要确保它可以工作,就需要付出额外的努力。 – 2014-09-11 20:13:23

+0

@RainerSchwarze我会记下这件事,谢谢。对于OpenOffice格式,我没有这样的问题。 – user1516873 2014-09-12 07:12:15

回答

2

HWPF不能用于写入.doc文件。它可能适用于非常简单的文件内容,但很少有额外功能会打破它。我担心你在这里运气不佳 - 如果这是你的选择,你可能想使用RTF文件并在这些文件上工作。如果将rtf扩展名重命名为.doc(如果需要.doc扩展名),Word应该可以正常工作。 (我为客户开发了一个HWPF的自定义和工作变体,并知道事情可能会有多困难。当使用8位编码以外的字符时,标准HWPF库会遇到麻烦,使用表时,何时当嵌入图形时,使用文本框... .doc文件中的一些内容也与Microsoft官方规范中描述的不同。使HWPF库成为“非平凡”并且需要大量spec-reading and investigation。如果你想要修复这些错误,你需要至少半年的开发工作。)

+0

感谢您对问题的详细描述。 – Alex85 2014-09-11 06:42:36

+0

是的,我使用了很多表格和标志,问题解决了,我以.odt格式保存文件并使用JODReports。输出文件中的所有格式文本 - 很好。 – Alex85 2014-09-11 06:58:22