public String exportXls() throws IOException{
//查询所有的分区数据
List<Entity> list = xlsService.findAll();
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//1.创建sheet
HSSFSheet sheet = hssfWorkbook.createSheet("sheetName");
//2.创建首行
HSSFRow headerRow = sheet.createRow(0);
//3.创建行内的每一个单元格 总共5列
headerRow.createCell(0).setCellValue("cellName1");
headerRow.createCell(1).setCellValue("cellName2");
headerRow.createCell(2).setCellValue("cellName3");
headerRow.createCell(3).setCellValue("cellName4");
headerRow.createCell(4).setCellValue("cellName5");
//4.遍历list,动态加入到单元格内
for (Entity entity : list) {
//每遍历一次,在末尾行动态添加一行
HSSFRow data = sheet.createRow(sheet.getLastRowNum()+1);
//动态添加数据
data.createCell(0).setCellValue(entity.getproperty1());
data.createCell(1).setCellValue(entity.getproperty2());
data.createCell(2).setCellValue(entity.getproperty3());
data.createCell(3).setCellValue(entity.getproperty4());
data.createCell(4).setCellValue(entity.getproperty5());
}
//5.添加完成后,使用输出流下载
ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
String filename="my.xls";
//实际上就是解析了tomcat web.xml MIME xls类型
String contentType = ServletActionContext.getServletContext().getMimeType(filename);
//设置文件的类型(后缀名)
ServletActionContext.getResponse().setContentType(contentType);
//设置响应头,指定下载的文件名
ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename="+filename);
//使用workbook提供的write方法
hssfWorkbook.write(out);
return NONE;
}