Apache Poi Word 简明教程

Apache POI Word - Document

此处,术语“文档”指的是 MS-Word 文件。完成本章后,你将能够创建新文档并使用 Java 程序打开现有文档。

Here the term 'document' refers to a MS-Word file. After completion of this chapter, you will be able to create new documents and open existing documents using your Java program.

Create Blank Document

以下简单程序用于创建一个空白 MS-Word 文档 −

The following simple program is used to create a blank MS-Word document −

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class CreateDocument {
   public static void main(String[] args)throws Exception  {
      //Blank Document
      XWPFDocument document = new XWPFDocument();

      //Write the Document in file system
      FileOutputStream out = new FileOutputStream( new File("createdocument.docx"));
      document.write(out);
      out.close();
      System.out.println("createdocument.docx written successully");
   }
}

将以上 Java 代码保存为 CreateDocument.java, ,然后从命令提示符编译并执行,如下所示 −

Save the above Java code as CreateDocument.java, and then compile and execute it from the command prompt as follows −

$javac  CreateDocument.java
$java CreateDocument

如果您的系统环境已配置 POI 库,它将编译并执行,在当前目录中生成一个名为 createdocument.docx 的空白 Word 文档文件,并在命令提示符中显示以下输出 −

If your system environment is configured with the POI library, it will compile and execute to generate a blank Word document file named createdocument.docx in your current directory and display the following output in the command prompt −

createdocument.docx written successfully