2010-04-07 72 views
26

我正在尋找一個簡單的示例代碼或完整的教程,瞭解如何使用Apache POI及其基礎openxml4j創建docx文件。如何使用Apache POI創建簡單的docx文件?

我試了下面的代碼(很多來自內容助手的幫助,感謝Eclipse!),但代碼無法正常工作。

String tmpPathname = aFilename + ".docx"; 
File tmpFile = new File(tmpPathname); 

ZipPackage tmpPackage = (ZipPackage) OPCPackage.create(tmpPathname); 
PackagePartName tmpFirstPartName = PackagingURIHelper.createPartName("/FirstPart"); 
PackagePart tmpFirstPart = tmpPackage.createPart(tmpFirstPartName, "ISO-8859-1"); 

XWPFDocument tmpDocument = new XWPFDocument(tmpPackage); //Exception 
XWPFParagraph tmpParagraph = tmpDocument.createParagraph(); 
XWPFRun tmpRun = tmpParagraph.createRun(); 
tmpRun.setText("LALALALAALALAAAA"); 
tmpRun.setFontSize(18); 
tmpPackage.save(tmpFile); 

拋出的異常如下:

Exception in thread "main" java.lang.NullPointerException 
    at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:235) 
    at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:196) 
    at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.java:94) 
    at DocGenerator.makeDocxWithPoi(DocGenerator.java:64) 
    at DocGenerator.main(DocGenerator.java:50) 

是否有人能幫助我與我的(很簡單)的要求?

+0

從哪裏獲得這個圖書館? – AkashG 2014-01-30 06:45:23

回答

31

這裏是你如何創建與POI一個簡單的docx文件:

XWPFDocument document = new XWPFDocument(); 
XWPFParagraph tmpParagraph = document.createParagraph(); 
XWPFRun tmpRun = tmpParagraph.createRun(); 
tmpRun.setText("LALALALAALALAAAA"); 
tmpRun.setFontSize(18); 
document.write(new FileOutputStream(new File("yourpathhere"))); 
document.close(); 
+0

我們可以刪除這個問題嗎?這太尷尬了...... 謝謝瓦倫丁! – guerda 2010-04-07 13:34:35

+7

哈哈不用擔心,這裏有很多愚蠢的問題(並且POI不是那麼容易使用) – 2010-04-07 14:33:50

+3

它只是幫助我,而我沒有出現錯誤,這是一個非常棒的Google搜索結果使用POI的例子。 – cgp 2010-11-03 13:50:34

1
import java.io.File; 
    import java.io.FileOutputStream; 
    import org.apache.poi.xwpf.usermodel.XWPFDocument; 
    import org.apache.poi.xwpf.usermodel.XWPFParagraph; 
    import org.apache.poi.xwpf.usermodel.XWPFRun; 
    public class DocFile { 
    public void newWordDoc(String filename, String fileContent) 
     throws Exception { 
     XWPFDocument document = new XWPFDocument(); 
     XWPFParagraph tmpParagraph = document.createParagraph(); 
     XWPFRun tmpRun = tmpParagraph.createRun(); 
     tmpRun.setText(fileContent); 
     tmpRun.setFontSize(18); 
     FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\amitabh\\Pictures\\pics\\"+filename + ".doc")); 
     document.write(fos); 
     fos.close(); 
    } 
    public static void main(String[] args) throws Exception { 
     DocFile app = new DocFile(); 
     app.newWordDoc("testfile", "Hi hw r u?"); 

    } 
    } 
相關問題