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> 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(); } }