【Java】CSVUtils

 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 }

 

posted @ 2016-10-19 15:56  多弗朗明哥  阅读(1025)  评论(0编辑  收藏  举报