2012-02-10 150 views
1

我試圖從一個Java應用程序創建一個word文檔,並且使用相同的Apache POI穩定版本3.7。當我嘗試更改段落的字體時,即使字體系列存在,我也遇到空指針異常。事實上,如果我調用任何字體家族的功能,它會給出一個n。。繼承人的代碼:Apache POI SetFontFamily

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import org.apache.poi.xwpf.usermodel.XWPFDocument; 
import org.apache.poi.xwpf.usermodel.XWPFParagraph; 
import org.apache.poi.xwpf.usermodel.XWPFRun; 

/** 
* 
* @author william 
*/ 
public class CreateDocumentFromScratch 
{ 

    public static void main(String[] args) 
    { 
     XWPFDocument document = new XWPFDocument(); 

     XWPFParagraph paragraphOne = document.createParagraph(); 


     XWPFRun paragraphOneRunOne = paragraphOne.createRun(); 

     paragraphOneRunOne.setFontFamily("Arial"); 
     paragraphOneRunOne.setText("Hello"); 



     FileOutputStream outStream = null; 
     try { 
      outStream = new FileOutputStream("c:/will/First.docx"); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

     try { 
      document.write(outStream); 
      outStream.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

這裏是個例外:

run: 
Exception in thread "main" java.lang.NullPointerException 
    at org.apache.poi.xwpf.usermodel.XWPFRun.setFontFamily(XWPFRun.java:413) 
    at pdftest.CreateDocumentFromScratch.main(CreateDocumentFromScratch.java:30) 

任何想法錯了我在幹嘛?另外,Apache POI如何可靠地創建格式化的文檔?

回答

2
+0

是的,我發現它。感謝反正oers!我已經下載了版本3.8.5,這是一個開發版本,它似乎在那裏工作。 Apache POI如何可靠地創建Word文檔? – Will 2012-02-10 09:41:46

+0

@我不知道我只用它作爲excel,但它通常是一個很好的框架 – oers 2012-02-10 09:45:20

+0

好的謝謝你的幫助@oers !!! – Will 2012-02-10 09:58:43