代碼
function toExcel(){ $("#formExcel").submit(); }
@RequestMapping(value="/toExcel",method=RequestMethod.POST) public String toExcel(HttpServletResponse response, String fileName, String tableName, String type, String where){ if (StringUtils.isNotEmpty(fileName) && StringUtils.isNotEmpty(tableName) && StringUtils.isNotEmpty(type)) { inteQueryService.toExcel(response,fileName,tableName,type,where); return null; } return null; }
public static void toExcel(HttpServletResponse response,List<Map<String,Object>> lists,String name,String[] strArr){ List[] totals = splitList(lists,65000); // 建立工做簿 HSSFWorkbook wb = new HSSFWorkbook(); // 由工做簿建立工做表 for (int j = 0; j < totals.length; j++) { HSSFSheet sheet = wb.createSheet("sheet"+(j+1)); // 在工做表中建立行 HSSFRow row = sheet.createRow(0); // 建立單元格,設置每一個單元格的字段名 HSSFCell cell = null; for (int i = 0; i < strArr.length; i++) { cell = row.createCell(i); cell.setCellValue(strArr[i]); } List<Map<String,Object>> list = totals[j]; for (int i = 0; i < list.size(); i++) { Iterator iter = list.get(i).entrySet().iterator(); row = sheet.createRow(i+1); cell = row.createCell(0); cell.setCellValue(i+1); int index = 1; while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); //Object key = entry.getKey(); Object val = entry.getValue(); cell = row.createCell(index); cell.setCellValue(val.toString()); index++; } } } ServletOutputStream sos = null; try { String fileName = name+".xls"; response.setContentType("application/vnk.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentType("application/msexcel;charset=utf-8"); response.resetBuffer(); sos = response.getOutputStream(); wb.write(sos); sos.flush(); } catch (IOException e) { logger.error("導出excel工具類報錯",e); } finally { try { sos.close(); } catch (IOException e) { logger.error("導出excel工具類報錯",e); } } }
public static List[] splitList(List list, Integer pageSize) { if(pageSize == null){ pageSize = 300; } int total = list.size(); //總頁數 int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1; List[] result = new List[pageCount]; for(int i = 0; i < pageCount; i++) { int start = i * pageSize; //最後一條可能超出總數 int end = start + pageSize > total ? total : start + pageSize; List subList = list.subList(start, end); result[i] = subList; } return result; }
常見問題
前臺必定要使用表單的方式進行提交,ajax是不行的,由於ajax只能接受 xml、 json、html等相似字符串的返回,不能接受流做爲返回值。不然程序不報錯,就是不彈下載框。javascript