用到的JAR包如下(可以直接到POI官網上下載也可以在文章的附件中下載):
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
xmlbeans-2.3.0.jar
可能有衝突的JAR包,如果工程lib中存在,需要刪除。
xbean-2.1.0.jar
具體代碼如下:
Java代碼
package com.mengwx; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * 匯入和匯出Excel檔案類 * 支援2003(xls)和2007(xlsx)版本的Excel檔案 * * @author mengwx */ public class ExcelForPOI { public static void main(String[] args) { // 檔案所在路徑 String execelFile = "C:/Book2007.xlsx" ; //String execelFile = "C:/Book2003.xls" ; // 匯入Excel new OperationExcelForPOI().impExcel(execelFile) ; // 匯出Excel String expFilePath = "C:/testBook.xls" ; new OperationExcelForPOI().expExcel(expFilePath); } /** * 匯入Excel * @param execelFile */ public void impExcel(String execelFile){ try { // 構造 Workbook 對象,execelFile 是傳入檔案路徑(獲得Excel工作區) Workbook book = null; try { // Excel 2007擷取方法 book = new XSSFWorkbook(new FileInputStream(execelFile)); } catch (Exception ex) { // Excel 2003擷取方法 book = new HSSFWorkbook(new FileInputStream(execelFile)); } // 讀取表格的第一個sheet頁 Sheet sheet = book.getSheetAt(0); // 定義 row、cell Row row; String cell; // 總共有多少行,從0開始 int totalRows = sheet.getLastRowNum() ; // 迴圈輸出表格中的內容,首先迴圈取出行,再根據行迴圈取出列 for (int i = 1; i <= totalRows; i++) { row = sheet.getRow(i); // 處理空行 if(row == null){ continue ; } // 總共有多少列,從0開始 int totalCells = row.getLastCellNum() ; for (int j = row.getFirstCellNum(); j < totalCells; j++) { // 處理空列 if(row.getCell(j) == null){ continue ; } // 通過 row.getCell(j).toString() 擷取儲存格內容 cell = row.getCell(j).toString(); System.out.print(cell + "\t"); } System.out.println(""); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void expExcel(String expFilePath){ OutputStream os = null ; Workbook book = null; try { // 輸出資料流 os = new FileOutputStream(expFilePath); // 建立工作區(97-2003) book = new HSSFWorkbook(); // 建立第一個sheet頁 Sheet sheet= book.createSheet("test"); // 產生第一行 Row row = sheet.createRow(0); // 給第一行的第一列賦值 row.createCell(0).setCellValue("column1"); // 給第一行的第二列賦值 row.createCell(1).setCellValue("column2"); // 寫檔案 book.write(os); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉輸出資料流 try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }