JAVA下载CVS文件(可直接复用)

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();
		}
    	
    }

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值