Apache Poi 简明教程
Apache POI - Workbooks
这里的术语“工作簿”意味着 Microsoft Excel 文件。完成本章后,您将可以用 Java 程序创建新工作簿并打开现有工作簿。
Here the term 'Workbook' means Microsoft Excel file. After completion of this chapter, you will be able to create new Workbooks and open existing Workbooks with your Java program.
Create Blank Workbook
以下简单程序用于创建一个空白 Microsoft Excel 工作簿。
The following simple program is used to create a blank Microsoft Excel Workbook.
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 ,然后按照以下步骤从命令提示符处进行编译和执行 -
Let us save the above Java code as CreateWorkBook.java, and then compile and execute it from the command prompt as follows −
$javac CreateWorkBook.java
$java CreateWorkBook
如果您的系统环境配置了 POI 库,它将编译和执行以在您当前的目录中生成名为 createworkbook.xlsx 的空白 Excel 文件,并在命令提示符中显示以下输出。
If your system environment is configured with the POI library, it will compile and execute to generate the blank Excel file named createworkbook.xlsx in your current directory and display the following output in the command prompt.
createworkbook.xlsx written successfully
Open Existing Workbook
使用以下代码打开现有的工作簿。
Use the following code to open an 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 然后从命令提示符编译并执行它,如下所示−
Save the above Java code as OpenWorkBook.java, and then compile and execute it from the command prompt as follows −
$javac OpenWorkBook.java
$java OpenWorkBook
它会编译并执行以生成以下输出。
It will compile and execute to generate the following output.
openworkbook.xlsx file open successfully.
打开工作簿后,您可以在其上执行读取和写入操作。
After opening a workbook, you can perform read and write operations on it.