导出excel 通过浏览器响应来实现
控制层
/**
*预警导出
*/
@RequestMapping(value = "excelExportWarning")
public void excelExportfightingWarning(@RequestBody JSONObject json,HttpServletResponse response) throws Exception {
ResultInfo resultInfo = new ResultInfo();
try {
resultInfo = mFireFightingWarningService.excelExportfightingWarning(json,response);
} catch (Exception e) {
e.printStackTrace();
resultInfo.setCode(MsgEnum.FAIL.getCode());
resultInfo.setMsg(MsgEnum.FAIL.getMsg());
}
}
业务层
public ResultInfo excelExportfightingWarning(JSONObject json,HttpServletResponse response) throws Exception {
//创建了一个excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
//创建了一个工作簿
HSSFSheet sheet = workbook.createSheet("预警信息表");
//设置要导出的文件的名字
//excel文件名
String fileName = "消防预警信息表"+System.currentTimeMillis()+".xls";
// 如果文件名有中文,必须URL编码
fileName = URLEncoder.encode(fileName, "UTF-8");
//新增数据行,并且设置单元格数据
int rowNum = 1;
String[] headers = {"预警时间","单位","州市","区县","预警种类","级别","状态"};
//headers表示excel表中第一行的表头
HSSFRow row = sheet.createRow(0);
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
HSSFFont font = workbook.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 12);//设置字体大小
style.setFont(font);
style.setFillForegroundColor(IndexedColors.CORNFLOWER_BLUE.getIndex());// 设置背景色
//在excel表中添加表头
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
HSSFCellStyle dateCellStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss");
dateCellStyle.setDataFormat(df);
//在表中存放查询到的数据放入对应的列
List<MFireFightingWarning> list = this.findPage(json);
for (MFireFightingWarning obj: list) {
HSSFRow row1 = sheet.createRow(rowNum);
row1.createCell(0).setCellValue(sdf.format(obj.getWarningTime()));
row1.createCell(1).setCellValue(obj.getCulturaCompanyName());
row1.createCell(2).setCellValue(obj.getCityName());
row1.createCell(3).setCellValue(obj.getDistrictName());
row1.createCell(4).setCellValue(obj.getWarningSpeciesName());
row1.createCell(5).setCellValue(obj.getWarningLevelName());
row1.createCell(6).setCellValue(WarningStatusEnum.getValue(obj.getStatus()));
rowNum++;
}
//设置头信息
// ContentType 可以不设置
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
workbook.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
return new ResultInfo();
}