java对CSV文件操作

依赖

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

CSV工具类以及测试

package com.example.demo.files;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.*;
import java.util.*;

/**
 * @describtion csv工具类
 * @create-time 9:43 2019/11/18
 **/
public class CsvUtil {
    
	/**
	* 导出csv
	*/
    public static OutputStream write(String filePath, String[] headers, List<List<String>> datas) throws IOException {
        FileOutputStream fos = new FileOutputStream(filePath);
        OutputStreamWriter out = new OutputStreamWriter(fos, "GBK");
        // 文件头
        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers);
        CSVPrinter printer = new CSVPrinter(out,csvFormat);
        System.out.println("start...");
        datas.forEach((list)-> {
            try {
                printer.printRecord(list);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        printer.flush();
        printer.close();
        out.close();
        fos.close();
        System.out.println("over...");
        return null;
    }
    
	/**
	*读csv
	*/
    public static List<CSVRecord> read(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader in = new InputStreamReader(fis);
        CSVParser parser = new CSVParser(in,CSVFormat.DEFAULT);
        List<CSVRecord> records = parser.getRecords();
        parser.close();
        in.close();
        fis.close();
        return records;
    }

    public static void main(String[] args) {
        String filepath = "G:"+File.separator+"write.csv";
        String[] headers = {"姓名","性别","公司","岗位"};
        List<List<String>> datas = new ArrayList<>();
        datas.add(Arrays.asList("lisi","nan","gg","java"));
        datas.add(Arrays.asList("zhangsan","nv","ba","c"));
        datas.add(Arrays.asList("wangwu","nan","tt","python"));
        try {
            CsvUtil.write(filepath,headers,datas);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
发布了59 篇原创文章 · 获赞 33 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41010294/article/details/103120614