public static void downLoad(HttpServletResponse response,//必传 List list,//必传 String title,//必传 String[] paramStr,//必传 String[] str, List<Map> filter){ if ( CollectionUtil.isEmpty(filter)){ downLoad(response, list, title, paramStr, str); return ; } if ( StrUtil.isBlank(title)|| ArrayUtil.isEmpty(paramStr)) { throw ExceptionConstant.bussinessException(ExceptionCodeEnum.dataExists); } ;//(参数有误) // 通过工具类创建writer,默认创建xlsx格式 ExcelWriter writer = ExcelUtil.getWriter(true); //得到有值得参数 int total=paramStr.length; //定义最后要写出的对象 List<Map> resultList=new ArrayList<Map>(); if (CollectionUtil.isNotEmpty(list)){ for (Object obj : list) { if (BeanUtil.isBean(obj.getClass())) { obj = BeanUtil.beanToMap(obj); } if (!obj.getClass().equals(HashMap.class) && (!obj.getClass().equals(LinkedHashMap.class))) { //将对象转换为map Map map = new LinkedHashMap(); //得到对应字段的值 for (String param : paramStr) { Object ob = ReflectUtil.getFieldValue(obj,param); String dat = Convert.toStr(ob); map.put(param, StrUtil.blankToDefault(dat," ")); } resultList.add(map); }else if (obj.getClass().equals(HashMap.class)||obj.getClass().equals(LinkedHashMap.class)){ //得到原始时间 Map thisMap= (Map)obj; //得到所有的key Set<String> set = thisMap.keySet(); //将set转为list List objects = Convert.toList(set); //将map中的数据导入 Map map = new LinkedHashMap(); for (String param : paramStr) { int index = objects.indexOf(param); if (index>=0){ String dat = Convert.toStr(thisMap.get(param)); map.put(param,StrUtil.blankToDefault(dat," ")); } } resultList.add(map); } } } //自定义标题别名 if( str !=null && str.length>0){ if( str.length ==total ) { int index=0; for (String param : paramStr) { writer.addHeaderAlias(param, str[index]); index++; } } } //设置标题 //writer.merge(total-1, ""); // 一次性写出内容,使用默认样式,强制输出标题 // 命名sheet writer.renameSheet("Data"); writer.write(resultList, true); writer.setSheet("Filter"); // 更改列名 writer.addHeaderAlias("title", "Filter"); writer.addHeaderAlias("value", "Value"); writer.write(filter); //writer.autoSizeColumnAll(); //response为HttpServletResponse对象
writer.write(resultList, true);
//加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
response.addHeader("Content-Length", resultList.size()+"");
response.setContentType("application/vnd.ms-excel;charset=utf-8"); //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 try { title = URLEncoder.encode(title, "UTF-8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { log.error("Excel download Error:",e); } response.setHeader("Content-Disposition", StrUtil.concat(false,"attachment;filename=",title,".xlsx")); try (ServletOutputStream out = response.getOutputStream()) { writer.flush(out); // 关闭writer,释放内存 writer.close(); //此处记得关闭输出Servlet流 IoUtil.close(out); }catch (IOException e){ throw ExceptionConstant.systemException(ExceptionCodeEnum.exportException,e); }