如何使用Apache POI创建一个简单的docx文件?

36
我正在寻找一个简单的示例代码或完整的教程,介绍如何使用Apache POI和其底层的openxml4j创建一个docx文件。
我尝试了以下代码(在Eclipse的Content Assist的帮助下进行了大量修改),但代码不能正常工作。
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)

有人可以帮我满足我的(非常简单的)需求吗?


我从哪里获取这个库? - AkashG
@AkashG 你可能需要多个库。大部分/全部Apache POI / OOXML的内容都在这里:https://mvnrepository.com/artifact/org.apache.poi(OOXML是构建Word的开源标准)。 - Sarah Messer
2个回答

44

以下是使用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();

8
哈哈,不要担心,这里有很多更傻的问题(而且POI并不是很容易使用)。 - Valentin Rocher
4
这个搜索结果对我很有帮助,虽然我没有遇到你所描述的错误。这是一个非常简单的使用POI的示例,非常棒。 - cgp
如何在Android中执行此操作,我的意思是通过上述代码在运行时创建docx文件是否可行? - AkashG
@guerda 嘿,我有POI版本3.10,但它在XWPF上不能工作。请告诉我我需要使用哪个确切的JAR文件。 - SoulRayder
@guerda :nvm:我没有添加 ooxml jar 包...现在已经可以工作了...不管怎样还是谢谢。 - SoulRayder
显示剩余4条评论

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

    }   
  }   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接