如何使用Apache POI创建一个简单的docx文件?
2022-09-01 06:54:29
我正在寻找一个简单的示例代码或一个完整的教程,如何使用Apache POI及其底层创建文件。docx
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)
有人可以帮助我满足我的(非常简单的)要求吗?