POI 导出 Excel

1.调用 Action 类中的 exproExcel 方法

public String exproExcel() throws Exception {
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("学生信息表");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

HSSFCell cell = row.createCell(0);
cell.setCellValue("序号");
cell.setCellStyle(style); //设置单元格居中

cell = row.createCell(1);
cell.setCellValue("用户名");
cell.setCellStyle(style); //设置单元格居中

cell = row.createCell(2);
cell.setCellValue("密码");
cell.setCellStyle(style); //设置单元格居中

cell = row.createCell(3);
cell.setCellValue("地址");
cell.setCellStyle(style); //设置单元格居中

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,
                      // 得到数据保存在list中
List<User> list = userService.selectUser();

for (int i = 0; i < list.size(); i++){

row = sheet.createRow((int) i + 1);
User user = (User) list.get(i);

sheet.autoSizeColumn(0); //根据内容自动调整单元格宽度 第一列
sheet.autoSizeColumn(1); //根据内容自动调整单元格宽度 第二列
sheet.autoSizeColumn(2); //根据内容自动调整单元格宽度 第三列
sheet.autoSizeColumn(3); //根据内容自动调整单元格宽度 第三列

// 第四步,创建单元格,并设置值
cell = row.createCell(0); //创建单元格
cell.setCellStyle(style); //设置单元格居中
cell.setCellValue(i+1); //将值放在单元格中

cell =row.createCell(1); //创建单元格
cell.setCellStyle(style); //设置单元格居中
cell.setCellValue(user.getName()); //将值放在单元格中

cell =row.createCell(2);//创建单元格
cell.setCellStyle(style); //设置单元格居中
cell.setCellValue(user.getPassword());//将值放在单元格中
}
// 第六步,将文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("E:/user.xls");
wb.write(fout);
fout.close();
System.out.println("导出成功");
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("导出失败");
}
return SUCCESS;
}

原文地址:https://www.cnblogs.com/zhanggaosong/p/2984913.html