代码贴出来,方便调试。
cell除了支持基础的数据类型外,还支持输出公式、图片、下拉菜单等特殊的单元格样式。下面会持续讲解。对于Cell中的内容如果需要换行,可以使用\n
符号。
// 创建工作簿
Workbook wb = new HSSFWorkbook(); //new XSSFWorkbook(); 分别是07和03对象
// 创建工作表,在工作簿对象中创建才可以,这里创建2个
Sheet sheet1 = wb.createSheet("工作表1");
Row row1 = sheet1.createRow(0);
// 数值类型
row1.createCell(0).setCellValue(100.10);
// 日期类型,将日期的值设置为等价的Excel表的值。
// 如果不设置日期格式,那么就是日期将变为数值
row1.createCell(1).setCellValue(new Date());
// 设置单元格的日期值
row1.createCell(2).setCellValue(Calendar.getInstance());
// 字符串类型
row1.createCell(3).setCellValue("string text");
// 布尔值类型
row1.createCell(4).setCellValue(true);
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
// 将创建好的Excel表格写出
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
结果