将数据导出csv文件并下载
1.导出csv文件方法
package com.demo.main; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; public class CsvUtil { // 文件位置(可使用参数传递的方式动态指定) private final static String path = "C:/member.csv"; /** * 导出 * * @param dataList 数据 * @param headdataList 标题数据数据 * @return */ public static boolean exportCsv(List<String> dataList,List<String> headdataList){ File file = new File(path); boolean isSucess=false; FileOutputStream out=null; OutputStreamWriter osw=null; BufferedWriter bw=null; try { if(!file.exists()){ file.createNewFile(); } out = new FileOutputStream(file); osw = new OutputStreamWriter(out); bw =new BufferedWriter(osw); if(headdataList!=null && !headdataList.isEmpty()){ for(String data : headdataList){ bw.append(data).append("\r"); } } if(dataList!=null && !dataList.isEmpty()){ for(String data : dataList){ bw.append(data).append("\r"); } } isSucess=true; } catch (Exception e) { isSucess=false; }finally{ if(bw!=null){ try { bw.close(); bw=null; } catch (IOException e) { e.printStackTrace(); } } if(osw!=null){ try { osw.close(); osw=null; } catch (IOException e) { e.printStackTrace(); } } if(out!=null){ try { out.close(); out=null; } catch (IOException e) { e.printStackTrace(); } } } return isSucess; } }
2.下载文件
/** * 下载csv文件 * * @param response */ public static void download(HttpServletResponse response) { try { // path是指欲下载的文件的路径。 File file = new File(path); // 取得文件名。 String filename = file.getName(); // 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/vnd.ms-excel;charset=gb2312"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } }
3.测试
@RequestMapping("/test.do") public void test(HttpServletRequest req, HttpServletResponse resp) throws Exception { List<String> heardataList=new ArrayList<String>(); heardataList.add("编号,姓名,性别"); List<String> dataList=new ArrayList<String>(); dataList.add("1,admin,男"); dataList.add("2,main,女"); dataList.add("3,test,男"); boolean isSuccess= CsvUtil.exportCsv( dataList,heardataList); CsvUtil.download(resp); }
4.注意
a.单个数据之间用英文逗号(,)隔开
b.使用文件下载的时候不可用异步访问,需要使用:
window.location.href=....
c.当输入手机号或者账号等数字过长的数据时,为避免出现科学记数法的问题,可在字符前面拼接“\t”,如:
dataList.add("4,"+"\t"+"12345678910,男");