1 package com.msk.ds.logic; 2 3 import java.io.*; 4 import java.util.List; 5 6 /** 7 * Created by Administrator on 2016/5/4. 8 */ 9 public class CSVUtils { 10 11 public static File createCSVFile(List<Object> head, List<List<Object>> dataList, String outPutPath, String filename) { 12 File csvFile = null; 13 BufferedWriter csvWtriter = null; 14 try { 15 csvFile = new File(outPutPath + File.separator + filename + ".csv"); 16 File parent = csvFile.getParentFile(); 17 if (parent != null && !parent.exists()) { 18 parent.mkdirs(); 19 } 20 csvFile.createNewFile(); 21 22 // GB2312使正确读取分隔符"," 23 csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( 24 csvFile), "UTF-8"), 1024); 25 // 写入文件头部 26 writeRow(head, csvWtriter); 27 28 // 写入文件内容 29 for (List<Object> row : dataList) { 30 writeRow(row, csvWtriter); 31 } 32 csvWtriter.flush(); 33 } catch (Exception e) { 34 e.printStackTrace(); 35 } finally { 36 try { 37 csvWtriter.close(); 38 } catch (IOException e) { 39 e.printStackTrace(); 40 } 41 } 42 return csvFile; 43 } 44 45 46 /** 47 * 写一行数据方法 48 * 49 * @param row 50 * @param csvWriter 51 * @throws IOException 52 */ 53 private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException { 54 // 写入文件头部 55 for (Object data : row) { 56 StringBuffer sb = new StringBuffer(); 57 String rowStr = sb.append(""").append(data).append("",").toString(); 58 csvWriter.write(rowStr); 59 } 60 csvWriter.newLine(); 61 } 62 }
1 /** 2 * 导出CSV数据 3 * @return 数据 4 */ 5 @RequestMapping(value = "dataExport",method = RequestMethod.POST) 6 public @ResponseBody int dataExport(HttpServletResponse response) throws IOException{ 7 List<DsPrintTask> list=sc182211Logic.findDataExport(); 8 // 设置表格头 9 Object[] head = {"任务编码", "操作码", "阅读码", "品牌名", "等级名"}; 10 List<Object> headList = Arrays.asList(head); 11 // 设置数据 12 List<List<Object>> dataList = new ArrayList<List<Object>>(); 13 List<Object> rowList = null; 14 for (int i = 0; i < list.size(); i++) { 15 rowList = new ArrayList<Object>(); 16 rowList.add(list.get(i).getPrintTaskId()); 17 rowList.add(list.get(i).getOperateBar()); 18 rowList.add(list.get(i).getReadBar()); 19 rowList.add(list.get(i).getBrandName()); 20 rowList.add(list.get(i).getGradeName()); 21 dataList.add(rowList); 22 } 23 String downloadFilePath ="D:/test"; 24 String fileName = "标签列表"; 25 // 导出CSV文件 26 CSVUtils.createCSVFile(headList, dataList, downloadFilePath, fileName); 27 28 29 30 response.setHeader("Content-Disposition", "attachment;filename=" 31 + "liq.csv"); 32 response.setContentType("application/csv;charset=GBK"); 33 34 File file = new File("D:/test/标签列表.csv"); 35 InputStream in = new FileInputStream(file); 36 int len = 0; 37 byte bytes[] = new byte[1024 * 8]; 38 while ((len = in.read(bytes)) != -1) { 39 response.getOutputStream().write(bytes, 0, len); 40 } 41 in.close();// 关闭流 .... 42 43 return NumberConst.IntDef.INT_ONE; 44 }