- Apache POI Tutorial
- Apache POI - Home
- Apache POI - Overview
- Apache POI - Java Excel APIs
- Apache POI - Environment
- Apache POI - Core Classes
- Apache POI - Workbooks
- Apache POI - Spreadsheets
- Apache POI - Cells
- Apache POI - Fonts
- Apache POI - Formula
- Apache POI - Hyperlink
- Apache POI - Print Area
- Apache POI - Database
- Apache POI Resources
- Apache POI - Questions & Answers
- Apache POI - Quick Guide
- Apache POI - Useful Resources
- Apache POI - Discussion
Apache POI - 工作簿
这里的术语“工作簿”是指 Microsoft Excel 文件。完成本章后,您将能够使用 Java 程序创建新的工作簿并打开现有的工作簿。
创建空白工作簿
以下简单程序用于创建空白的 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
打开现有工作簿
使用以下代码打开现有工作簿。
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.
打开工作簿后,可以对其进行读写操作。