代码之家  ›  专栏  ›  技术社区  ›  guerda

如何使用apache poi创建一个简单的docx文件?

  •  29
  • guerda  · 技术社区  · 14 年前

    我正在搜索一个简单的示例代码或完整的教程,如何创建 docx 使用apache poi及其底层的文件 openxml4j

    我尝试了以下代码 很多 来自内容辅助的帮助,谢谢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)
    

    有人能帮我满足我的(非常简单的)要求吗?

    2 回复  |  直到 8 年前
        1
  •  35
  •   Valentin Rocher    8 年前

    以下是如何使用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();
    
        2
  •  1
  •   Amitabh Ranjan    11 年前
    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?");   
    
        }   
      }