Apache的POI網址 : http://poi.apache.org/index.html

現在Apache的POI已經可以做到操作2007版的 xlsx 的副擋名格式,

需要的Jar擋包含了(目前下載了3.10的Beta版)

1. poi-3.10-beta2.jar

以上單獨的檔案可以直接操作副檔名為xls的檔案,

2. poi-ooxml-3.10-beta2.jar

3. xmlbeans-2.3.0.jar

4. stax-api-1.0.1.jar

5. dom4j-1.6.1.jar

以上四個檔案必須要都包含才可以操作xlsx的檔案。

 

Apache 的Examples 網址 : http://poi.apache.org/spreadsheet/examples.html

 

一、新建檔案 :

  1. 副檔名XLS檔案

    Workbook wb = new org.apache.poi.hssf.usermodel.HSSFWorkbook();
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

  2. 副檔名XLSX檔案

    Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut); 
    fileOut.close();

二、 讀取Excel檔案:

  1. 不需判斷檔案 :

//透過File取得檔案的方式是比FileInputStream使用更少的memory
     //透過WorkbookFactory是最簡單的方式
     Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
     Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xls"));

  2. XLS 檔案 :

     //如果要使用HSSFWorkbook 的話
     //File
     NPOIFSFileSytem fs = new NPOIFSFileSystem(new File("file.xls"));
     HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot());
     //FileInputStream
     NPOIFSFileSytem fs = new NPOIFSFileSystem(myInputStream);
     HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot());

  3. XLSX檔案 :

     //如果要使用XSSFWorkbook的話
     //File
     OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
     XSSFWorkbook wb = new XSSFWorkbook(pkg);
     //FileInputStream
     NPOIFSFileSytem fs = new NPOIFSFileSystem(myInputStream);
     HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot());
     

     pkg.close();






arrow
arrow
    文章標籤
    excel java apache poi xlsx
    全站熱搜

    werwolf 發表在 痞客邦 留言(1) 人氣()