首先,我们要重点说明一下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)
关于*.xls与*.xlsx的更多区别可参考(*_翻_墙_):http://www.differencebetween.net/technology/difference-between-xls-and-xlsx/
#说明:-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/