Apache POI —— HSSF / XSSF(1)
新建工作薄(NewWorkbook)
?
Workbook wb =new?HSSFWorkbook();
FileOutputStream fileOut =new?FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
?
Workbook wb =new?XSSFWorkbook();
FileOutputStream fileOut =new?FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.close();
?
新建工作表(New Sheet)
Workbook wb =new?HSSFWorkbook();// or new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
//请注意,Excel工作表名称不得超过31个字符
//且不能包含任何如下字符:
// 0x0000
// 0x0003
//冒号colon (:)
//反斜杠backslash (\)
//星号asterisk (*)
//问号question mark (?)
//斜杠forward slash (/)
//打开方括号opening square bracket ([)
//关闭方括号closing square bracket (])
?
//可以使用org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}
//一个安全的方式用来创建工作表名,它将用空格('')替换无效字符
String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]");?// returns " O'Brien's sales??"
Sheet sheet3 = wb.createSheet(safeName);
?
FileOutputStream fileOut =new?FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
?
?
创建列(Creating Cells)
Workbook wb =new?HSSFWorkbook();
// Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
?
//创建一行,行号从0开始
Row row = sheet.createRow(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();
创建列数据(CreatingDate Cells)
Workbook wb =new?HSSFWorkbook();
// Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
?
//创建一行
Row row = sheet.createRow(0);
?
//创建一列并设置一个日期值,这一个列是没有样式的
Cell cell = row.createCell(0);
cell.setCellValue(new?Date());
?
//为第二列指定列样式?
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new?Date());
cell.setCellStyle(cellStyle);
?
//还可以使用java.util.Calendar设置日期
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);
?
//输出到文件
FileOutputStream fileOut =new?FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();