2014-09-10 76 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