1 public boolean downloadExcel(String title, String[] excelHeaderChName, 2 String[] header, List<Map<String, String>> content, 3 HttpServletResponse response) { 4 try { 5 String name = java.net.URLEncoder.encode(title, "UTF8"); 6 String filename = name 7 + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()); 8 filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); 9 response.reset(); 10 response.setCharacterEncoding("utf-8"); 11 response.setContentType("application/msexcel");// 设置为下载application/x-download 12 response.setHeader("Content-Disposition", "inline;filename=\"" 13 + filename + ".xls\""); 14 OutputStream os = response.getOutputStream(); 15 16 WritableWorkbook wwb = Workbook.createWorkbook(os); 17 // 创建excel工作表,指定名字和位置 18 WritableSheet sheet = wwb.createSheet(title, 0); 19 20 // 生成表头(行宽) 21 for (int i = 0; i < header.length; i++) { 22 sheet.addCell(new Label(i, 0, excelHeaderChName[i])); 23 // 设置excel列宽 24 sheet.setColumnView(i, 15); 25 } 26 27 // 内容 28 for (int i = 0; i < content.size(); i++) { 29 for (int j = 0; j < content.get(i).size(); j++) { 30 sheet.addCell(new Label(j, i + 1, content.get(i).get( 31 header[j]) 32 + "")); 33 } 34 } 35 36 // 写入工作表 37 wwb.write(); 38 wwb.close(); 39 os.close(); 40 } catch (IOException | WriteException e) { 41 e.printstackTrace(); 42 } 43 return true; 44 }
@param title excel文件名
@param excelTopName 表头中文名字(显示在第一行的中文表头内容)
@param header 表头字段属性(根据该属性获取对应的属性值,表头内容作为key值,根据该key值循环获取内容)
@param content 内容
@param response 响应