xlsx
Apache的POI網址:http://poi.apache.org.index.html
現在Apache的POI已經可以做到操作2007版的xlsx的副檔名格式,需要的jar檔包含了
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的檔案
一、新建檔案
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.xlsx");
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
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("file.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot());
//FileInputStream
NPOIFSFileSystem fs = new NPOIFSFileSystem(myInputStream);
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot());
3.xlsx檔案
//File
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
//FileInputStream
NPOIFSFileSystem fs = new NPOIFSFileSystem(myInputStream));
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot());
pkg.close();