Spring 导出 Excel

来源:互联网 发布:wephone创始人 知乎 编辑:程序博客网 时间:2024/06/07 12:28

Spring 4.3.7 导出Excel 方法,导出excel 使用的jar 为原生apache poi jar 文件

一开始网上找导出excel的方法,发现在Spring 的不同版本方法是不同的!

@RequestMapping(value="/exportExcel",method = RequestMethod.GET) public AbstractExcelView exportExcel(HttpServletResponse response) { String excelFileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();response.reset();response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "attachment; filename="+ excelFileName + ".xls");try{return new AbstractExcelView() {  @Overrideprotected void buildExcelDocument(Map<String, Object> arg0, HSSFWorkbook workbook, HttpServletRequest request,HttpServletResponse response) throws Exception {List<User> list = UserService.selectAll(); // 查询数据库获取所有用户列表addSheet(workbook.createSheet("Sheet1"), list);}/** * 填充excel 方法  遍历List<User> 填充 Sheet1 * @param sheet * @param list */private void addSheet(Sheet sheet, List<User> list) {  int rowNum=0;          Row row0 = sheet.createRow(rowNum++);          row0.createCell(0).setCellValue("编号");          row0.createCell(1).setCellValue("名字");          for (User excel : list) {              Row row = sheet.createRow(rowNum++);              row.createCell(0).setCellValue(excel.getId());              row.createCell(1).setCellValue(excel.getName());          }      }         };  }catch(Exception e){logger.error("导出excel错误", e);return null;}} 



原创粉丝点击