1、下载公共方法
/*** 导出* @param sTitle* @param fName* @param mapKey* @param response* @throws ServletRequestBindingException
*/
public static void exportCsv(String sTitle,String fName,String mapKey,List<Map<String, Object>> dataList,HttpServletResponse response) throws ServletRequestBindingException {try (final OutputStream os = response.getOutputStream()) {CSVUtils.responseSetProperties(fName, response);CSVUtils.doExport(dataList, sTitle, mapKey, os);} catch (Exception e) {//log.info("下载失败了......");}
}/*** @throws UnsupportedEncodingException* * setHeader
*/
public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {// 设置文件后缀SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");String fn = fileName + sdf.format(new Date()).toString() + ".csv";
// 读取字符编码String utf = "UTF-8";
// 设置响应response.setContentType("application/ms-txt.numberformat:@");response.setCharacterEncoding(utf);response.setHeader("Pragma", "public");
// response.setHeader("Cache-Control", "max-age=30");response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
}/** CSV文件列分隔符 */
private static final String CSV_COLUMN_SEPARATOR = ",";/** CSV文件列分隔符 */private static final String CSV_RN = "\r\n";/**CSV文件编码*/private static final String CSV_CODE="gbk";/*** * @param dataList 集合数据* @param colNames 表头部数据* @param mapKey 查找的对应数据* @param response 返回结果* @throws IOException */
public static boolean doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) throws IOException {
try {
StringBuffer buf = new StringBuffer();
String[] colNamesArr = null;
String[] mapKeyArr = null;
colNamesArr = colNames.split(",");
mapKeyArr = mapKey.split(",");
// 完成数据csv文件的封装
// 输出列头
for (int i = 0; i < colNamesArr.length; i++) {buf.append(colNamesArr[i]).append(CSV_COLUMN_SEPARATOR);
}buf.append(CSV_RN);if (null != dataList) { // 输出数据for (int i = 0; i < dataList.size(); i++) {for (int j = 0; j < mapKeyArr.length; j++) {if(dataList.get(i).get(mapKeyArr[j])==null){buf.append("").append(CSV_COLUMN_SEPARATOR);}else{if(dataList.get(i).get(mapKeyArr[j]) instanceof Timestamp){Timestamp t=(Timestamp)dataList.get(i).get(mapKeyArr[j]);SimpleDateFormat sf =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");buf.append(sf.format(new Date(t.getTime()))).append(CSV_COLUMN_SEPARATOR);}else{buf.append(dataList.get(i).get(mapKeyArr[j])).append(CSV_COLUMN_SEPARATOR);}}
}buf.append(CSV_RN);
}
}
// 写出响应os.write(buf.toString().getBytes("GBK"));return true;} catch (Exception e) {logger.error("doExport错误...", e);}finally{os.flush();os.close();}return false;}
2、引用
/*** 下载稽核指标详情结果* @param model* @param request* @param response* @throws UnsupportedEncodingException */@RequestMapping(value="downLoadResult",method=RequestMethod.GET)public void downLoadResult(Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam("mdName")String mdName, SysDmAuditIndicDetailResultsVo vo) throws UnsupportedEncodingException{vo.setMdName(URLDecoder.decode(mdName,"utf-8"));vo.setIsLimit(1);//字段名SysDmAuditIndicDetailResultsVo info = sysDmAuditIndicResultsService.getAuditColNames(vo);//中文名String[] colName = info.getColName().split(",");//英文字段String[] auditInfo = info.getAuditInfo().split(",");StringBuffer sTitle = new StringBuffer();StringBuffer mapKey = new StringBuffer();sTitle.append("稽核规则ID,稽核名称,数据周期");mapKey.append("auditRulesId,mdName,dataCycle");for(int i = 0;i<colName.length;i++){sTitle.append(","+colName[i]);mapKey.append(","+auditInfo[i]);}String fName = "稽核指标详情结果_"+info.getAuditRulesId()+"_"+System.currentTimeMillis();//详情List<SysDmAuditIndicDetailResultsVo> resultInfo = sysDmAuditIndicResultsService.getAuditDetailResultByMdId(vo);List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();Map<String,Object> map = null;for(int k=0;k<resultInfo.size();k++){map = new HashMap<String,Object>();map.put("auditRulesId", "\t"+resultInfo.get(k).getAuditRulesId());map.put("mdName", "\t"+resultInfo.get(k).getMdName());map.put("dataCycle", "\t"+resultInfo.get(k).getDataCycle());String[] detail = resultInfo.get(k).getIndicDetailResults().split(",");for(int j=0;j<detail.length;j++){map.put(auditInfo[j], "\t"+detail[j]);}dataList.add(map);}try {DownLoadUtils.exportCsv(sTitle.toString(), fName, mapKey.toString(), dataList, response);System.out.println("下载成功!");} catch (ServletRequestBindingException e) {e.printStackTrace();}}