2011-05-27 1952 views
2

我是POI API的新手,因此無論何時我使用HWPFDocument類記錄由HWPF文檔創建的.doc文件中的文本,所生成的doc文件只有一個字母,而不是整個文本,我寫道。如何使用POI hwpfdocument在java中的.doc文件中編寫大量文本

所以請給我如何添加更多文本的答案。

這是代碼:

/** 
      * Create a POIFSFileSystem from an InputStream. 
      * Test.doc is an empty doc with no contents 
      */ 
      POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("test.doc")); 

      /** 
      * Horrible word Document Format 
      */ 
      HWPFDocument hwpfDocument = new HWPFDocument(fs); 
      /** 
      * range is used for getting the range of the document except header and footer 
      */ 

      Range range = hwpfDocument.getRange(); 
      range.numParagraphs(); 
      /** 
      * creating Paragraph 
      */ 
      /** 
      * Inserts a paragraph into the end of this range. 
      * ParagraphProperties -> for creating Paragraph, index of the paragraph 
      */ 
      /*Paragraph paragraph1 = range.insertBefore(new ParagraphProperties(), 0); 

      paragraph1.setJustification((byte) 0); // 0-left, 1-center, 2-right, 3-left and right*/ 
      CharacterRun characterRun1 = range.insertBefore("Document"); 
      /** 
      * setting the font size 
      */ 
      characterRun1.setFontSize(2 * 12); // takes as an argument half points 
      /** 
      * making Text Bold Italic 
      */ 
      characterRun1.setBold(true); 
      characterRun1.setItalic(true); 
      characterRun1.setColor(111); 
      characterRun1.setData(true); 
      //characterRun1.replaceWith("Document"); 

      hwpfDocument.write(new FileOutputStream("hpwf-create-doc.doc", true)); 
+2

請添加您的當前代碼。 – RonK 2011-05-27 08:06:28

回答

0

如果可以,使用HWPFDocument到XWPFDocument開關(產生的.docx代替一個.doc)。 .docx格式非常好用(基於XML而不是二進制),因此POI通常會做得更好。

否則,請嘗試使用更簡單的模板文檔。文件格式這個詞對於各種各樣的位都是非常挑剔的,而且很可能您已經遇到過POI沒有意識到需要更新文件中的某些內容的情況,然後單詞會默默地反對。

+0

當我使用XWPFDocument而不是HWPFDocument時,則可以編寫大文本,但不能使用任何類型的富文本,即使用XWPFDocument的addPicture選項時,圖片肯定存在於文檔中,但它永遠不會顯示在如此形成的文件中。如何處理這個問題? – 2011-05-30 08:41:48

+0

嘗試升級? Stefan在最近的XWPF圖片上做了相當多的工作。此外,您想要將圖片添加到運行中,而不是整個文檔,因此它顯示正確。 – Gagravarr 2011-05-30 10:22:33

相關問題