将列表导出成一个excel文件
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
1 新建文件
// 创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//创建新的sheet对象(Excel表单)
HSSFSheet sheet = wb.createSheet();
2设置表头
//在sheet中创建第一行,参数为行索引
HSSFRow headRow = sheet.createRow(0);
fields.add("用户昵称");
fields.add("类型");
fields.add("简介");
fields.add("关注时间");
//设置表头内容
for(int i = 0; i < fields.size(); i++){
HSSFCell cell = headRow.createCell(i);
cell.setCellValue(fields.get(i));
}
3填写具体数据
//在sheet中添加每一行的具体信息
for(int j = 0; j < followList.size(); j++){
HSSFRow row = sheet.createRow(j+1);
UserFollowAndFollowerVO followInfo = followList.get(j);
row.createCell(0).setCellValue(followInfo.getNickName());
row.createCell(1).setCellValue(Constants.userFollowTypeMap.get(followInfo.getFollowType()));
row.createCell(2).setCellValue(followInfo.getDesc());
row.createCell(3).setCellValue(followInfo.getFollowTime().toLocalDateTime().format(formatter));
}
4构造响应
//输出,Content-Disposition激活文件下载对话框,文件名框自动填充了指定的文件名(UserData.xls)
//后三行确保没有做过关于禁止浏览器缓存的操作
response.setHeader("Content-Disposition", "attachment;filename=FollowList.xls");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream output = response.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(output);
bufferedOutputStream.flush();
wb.write(bufferedOutputStream);
bufferedOutputStream.close();