Apache Poi 简明教程

Apache POI - Workbooks

这里的术语“工作簿”意味着 Microsoft Excel 文件。完成本章后,您将可以用 Java 程序创建新工作簿并打开现有工作簿。

Create Blank Workbook

以下简单程序用于创建一个空白 Microsoft Excel 工作簿。

import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class CreateWorkBook {
   public static void main(String[] args)throws Exception {
      //Create Blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook();

      //Create file system using specific name
      FileOutputStream out = new FileOutputStream(new File("createworkbook.xlsx"));

      //write operation workbook using file out object
      workbook.write(out);
      out.close();
      System.out.println("createworkbook.xlsx written successfully");
   }
}

让我们将上面的 Java 代码保存为 CreateWorkBook.java ,然后按照以下步骤从命令提示符处进行编译和执行 -

$javac CreateWorkBook.java
$java CreateWorkBook

如果您的系统环境配置了 POI 库,它将编译和执行以在您当前的目录中生成名为 createworkbook.xlsx 的空白 Excel 文件,并在命令提示符中显示以下输出。

createworkbook.xlsx written successfully

Open Existing Workbook

使用以下代码打开现有的工作簿。

import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class OpenWorkBook {
   public static void main(String args[])throws Exception {
	   try {
         File file = new File("openworkbook.xlsx");
         FileInputStream fIP = new FileInputStream(file);

         //Get the workbook instance for XLSX file
         XSSFWorkbook workbook = new XSSFWorkbook(fIP);

         if(file.isFile() && file.exists()) {
            System.out.println("openworkbook.xlsx file open successfully.");
         } else {
            System.out.println("Error to open openworkbook.xlsx file.");
         }
      } catch(Exception e) {
         System.out.println("Error to open openworkbook.xlsx file." + e.getMessage());
      }
   }
}

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

$javac OpenWorkBook.java
$java OpenWorkBook

它会编译并执行以生成以下输出。

openworkbook.xlsx file open successfully.

打开工作簿后,您可以在其上执行读取和写入操作。