您的位置:首页 > 其它

POI操作Excel--创建单元格并写入内容--day02

2019-02-28 18:36 295 查看

创建单元格

1. 分析:

day01的时候已经创建了Excel工作簿和sheet, 接下来我们要写入内容。要写入内容,我们首先要创建行,然后再创建单元格,最后在单元格写入内容。

2.开发步骤

[code]/**
* 创建单元格
*/
@Test
public void createCell() {
// 创建Excel工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 设置日期格式, 当向单元格添加Date类型时,按照指定格式展示
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyyMMdd"));

// 创建sheet
HSSFSheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("第一页?"));

// 创建row, 从第0行开始
HSSFRow row = sheet.createRow(0);

// 创建单元格cell并写入内容
row.createCell(0).setCellValue(1);
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue(true);
HSSFCell cell = row.createCell(3);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
// 如果希望单元格写入富文本, 可以通过workBook获取工具类: HSSFCreationHelper
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
row.createCell(4).setCellValue(creationHelper.createRichTextString("这是富文本"));

// 创建输出流, 写出, 关闭流
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("demo8.xls");
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (workbook != null) {
workbook.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

3.效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: