此处的“Workbook”是指Microsoft Excel文件。在完成本章之后,您将能够使用Java程序创建新的工作簿并打开现有的工作簿。

创建空白工作簿

下面的简单程序用于创建空白的Microsoft Excel工作簿。

  1. import java.io.*;
  2. import org.apache.poi.xssf.usermodel.*;
  3.  
  4. public class CreateWorkBook {
  5. public static void main(String[] args)throws Exception {
  6. //Create Blank workbook
  7. XSSFWorkbook workbook = new XSSFWorkbook();
  8.  
  9. //Create file system using specific name
  10. FileOutputStream out = new FileOutputStream(new File("createworkbook.xlsx"));
  11.  
  12. //write operation workbook using file out object
  13. workbook.write(out);
  14. out.close();
  15. System.out.println("createworkbook.xlsx written successfully");
  16. }
  17. }

让我们将上面的Java代码保存为CreateWorkBook.java,然后从命令提示符下编译并执行它,如下所示:

  1. $javac CreateWorkBook.java
  2. $java CreateWorkBook

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

  1. createworkbook.xlsx written successfully

打开现有工作簿

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

  1. import java.io.*;
  2. import org.apache.poi.xssf.usermodel.*;
  3.  
  4. public class OpenWorkBook {
  5. public static void main(String args[])throws Exception {
  6. File file = new File("openworkbook.xlsx");
  7. FileInputStream fIP = new FileInputStream(file);
  8.  
  9. //Get the workbook instance for XLSX file
  10. XSSFWorkbook workbook = new XSSFWorkbook(fIP);
  11.  
  12. if(file.isFile() && file.exists()) {
  13. System.out.println("openworkbook.xlsx file open successfully.");
  14. } else {
  15. System.out.println("Error to open openworkbook.xlsx file.");
  16. }
  17. }
  18. }

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

  1. $javac OpenWorkBook.java
  2. $java OpenWorkBook

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

  1. openworkbook.xlsx file open successfully.

After opening a workbook, you can perform read and write operations on it.