java实现CSV生成

java实现导出csv功能,首先引入maven依赖:

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-csv</artifactId>
   <version>1.6</version>
</dependency>

然后看代码:

/**
* @param filePath  文件路径
* @param list      数据集合
* @param header    表头
*/
public static void write(String filePath,List<LinkedHashMap<String, String>> list,String... header) {
    try {
       FileOutputStream fos = new FileOutputStream(filePath);
       OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
       CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header);
       CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
       //跟上面两行代码是一样的
       //CSVPrinter csvPrinter = CSVFormat.DEFAULT.withHeader(header).print(osw);
       for (Map<String, String> map : list) {
           csvPrinter.printRecord(map.values());
       }
       csvPrinter.flush();
       csvPrinter.close();
    } catch (IOException e) {
       e.printStackTrace();
    }
}

如果是分多次写入csv,那么可能每个文件的第一次写入需要重新格式化文件写入,后续就进行追加:

/**
* @param filePath   文件路径
* @param list       数据集合 
* @param i          第几次写入
* @param header     表头
*/
public static void writeAppend(String filePath,List<LinkedHashMap<String, String>> list,int i,String... header) {
    try {
       FileOutputStream fos = null;
       if (i>0) {
          //追加数据
          fos = new FileOutputStream(filePath,true);
       }else {
           //重新写入
           fos = new FileOutputStream(filePath,false);
       }
       OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
       CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header);
       CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
       //跟上面两行代码是一样的
       //CSVPrinter csvPrinter = CSVFormat.DEFAULT.withHeader(header).print(osw);
       for (Map<String, String> map : list) {
           csvPrinter.printRecord(map.values());
       }
       csvPrinter.flush();
       csvPrinter.close();
    } catch (IOException e) {
       e.printStackTrace();
    }
}