歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java開發中使用POI庫操作Excel

Java開發中使用POI庫操作Excel

日期:2017/3/1 9:16:23   编辑:Linux編程

首先,我們要重點說明一下Excel的兩中不同的格式,這個直接影響到我們在使用POI操作Excel的方式。一定要先明確你要操作的Excel所使用的版本,切記!

1,Excel的兩種格式區別

a),*.xls文件是使用Microsoft Excel 2003或之前版本保存的電子表格,使用的存儲格式為BIFF (Binary Interchange File Format),一種特殊的二進制格式文件。

b)*.xlsx文件是使用Microsoft Office 2007 或後續版本保存的電子表格,使用的存儲格式為OOXML(Office Open XML),一種壓縮過的格式(通過十六進制編輯器UltraEdit可以看到其文件頭為#504B0304)

#說明:-03為2003版本或之前,07+為2007版本或後續

2,使用POI新建Excel

a),新建工作簿:

//-03
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
//07+
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.close();

b),新建表

Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");

//WorkbookUtil類可以檢查你的表名是否合法
String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]");
Sheet sheet3 = wb.createSheet(safeName);

FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

c),新建單元格

Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

//在表格第一行新建一行(注意其索引從0開始)
Row row = sheet.createRow((short)0);
//在第一行的第一列新建單元格,並設置其內容為1(注意其索引從0開始)
Cell cell = row.createCell(0);
cell.setCellValue(1);

//另一種更簡潔的創建方式
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);

//將表格輸出到文件
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

3,使用POI讀取Excel

//-03
InputStream inp = new FileInputStream("workbook.xls");
//07+
//InputStream inp = new FileInputStream("workbook.xlsx");

Workbook wb = WorkbookFactory.create(inp);
//獲取文件的第一個表(注意下標為0)
Sheet sheet = wb.getSheetAt(0);
//獲取第三行
Row row = sheet.getRow(2);
//獲取第三行的第四個單元格
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");

FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

更多關於POI的操作請參考官方文檔:http://poi.apache.org/

Copyright © Linux教程網 All Rights Reserved