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