Frage

Ich bin für ein einfaches Beispiel-Code oder ein komplettes Tutorial Suche, wie man eine docx Datei mit Apache POI und die ihr zugrunde liegenden openxml4j erstellen.

Ich habe versucht, den folgenden Code (mit viel Hilfe aus dem Content Assist dank Eclipse-!), Aber der Code nicht richtig funktioniert.

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);

Die geworfene Ausnahme ist die folgende:

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)

Hat jemand kann mir helfen, mit meinen (sehr einfach) Anforderungen?

War es hilfreich?

Lösung

Hier ist, wie Sie eine einfache docx-Datei mit POI erstellen:

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();

Andere Tipps

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?");   

    }   
  }   
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top