ChenJiaHe
2020-11-02 7623a26be989de427099ff13dc27183db95f13a6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.hx.util;
 
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
 
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
 
/**
 * CVS工具类
 * 
 * @author mgchen
 *
 */
public class CVSUtil {
 
    public void writeToCVS() throws Exception {
        FileOutputStream fos = new FileOutputStream("E:/cjsworkspace/cjs-excel-demo/target/abc.csv");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
 
        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("姓名", "年龄", "家乡");
        // CSVFormat.DEFAULT.withHeader(header)
        CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
 
        // csvPrinter = CSVFormat.DEFAULT.withHeader("姓名", "年龄", "家乡").print(osw);
 
        for (int i = 0; i < 10; i++) {
            csvPrinter.printRecord("张三", 20, "湖北");
        }
 
        csvPrinter.flush();
        csvPrinter.close();
 
    }
 
    public static void writeToCVS(String path, String[] headers, List<List<Object>> data) throws Exception {
        FileOutputStream fos = new FileOutputStream(path);
        byte[] uft8bom = { (byte) 0xef, (byte) 0xbb, (byte) 0xbf };
        fos.write(uft8bom);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
 
        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers);
        CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
 
        for (int i = 0; i < data.size(); i++) {
            csvPrinter.printRecord(data.get(i));
        }
 
        csvPrinter.flush();
        csvPrinter.close();
        osw.close();
        fos.close();
 
    }
}