Apache POI工作簿
此處的術語“Workbook”指的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 { 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."); } } }
保存上麵的Java代碼為OpenWorkBook.java,然後編譯並從命令提示符如下執行它:
$javac OpenWorkBook.java $java OpenWorkBook
這將編譯和執行生成以下輸出。
openworkbook.xlsx file open successfully.
打開工作簿後,可以進行讀取,並在上麵寫操作。