//-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();
//-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/