如何创建与Apache POI简单的docx文件?
-
25-09-2019 - |
题
我在寻找一个简单的例子代码或一个完整的教程如何创建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)
没有任何人能帮助我与我的(很简单)的要求?
解决方案
下面是如何创建与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();
其他提示
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?");
}
}
不隶属于 StackOverflow