java操作csv [vaynexiao]

简介

csv只需要建一个txt,输入以下内容,后缀改为csv即可:
姓名,年龄,身高,ID,地址
UZI,23,177,RNG-uzi,中国
Faker,19,178,hide on bush,韩国

或者新建一个excel文件,输入以上内容,另存为csv类型。

csv与excel文件区别就是,前者文本文件,后者二进制文件

public class TestWrite {
    public static void main(String[] args) throws IOException {
        String[] header = new String[]{"编码", "部门名称", "领导编号"};
        CSVFormat csvFormat = CSVFormat.DEFAULT
                .withHeader(header)
                .withSkipHeaderRecord()
                .withDelimiter(',');
        Appendable out = new PrintWriter("C:\\java\\new.csv");
        //CSVFormat csvFormat = CSVFormat.newFormat(',').withHeader(header).withSkipHeaderRecord();
        // 注意 使用 DEFAULT 创建的CSVFormat对象生成记录可以自动换行,
        // 如果使用上面的 newFormat 的csvformat 不会自动换行
        //  CSVPrinter csvPrinter = CSVFormat.DEFAULT.print(out);
         CSVPrinter csvPrinter = new CSVPrinter(out, csvFormat);

        List<String> records = new ArrayList<>();
        records.add("dept001" + "," + "产品部" + "," + "RSA001");
        records.add("dept002" + "," + "设计部" + "," + "RSA002");
        records.add("dept003" + "," + "技术部" + "," + "RSA003");
        records.add("dept004" + "," + "运营部" + "," + "RSA004");
        records.add("dept005" + "," + "财务部" + "," + "RSA005");
        for (String record : records) {
            csvPrinter.printRecord(record);
        }
        csvPrinter.flush();
        csvPrinter.close();
    }
}

public class TestRead {
    public static void main(String[] args) throws IOException {
        String[] header = new String[]{"姓名", "年龄", "身高", "ID", "地址"};
        String FILE_NAME = "data.csv";
        // 注意 : withSkipHeaderRecord 这里要设置跳过 header, 否则会吧 header 当成第一行记录
        CSVFormat csvFormat = CSVFormat.DEFAULT
                .withHeader(header)
                .withSkipHeaderRecord()
                // 如果默认分隔符不是,则需要手动设置
                .withDelimiter(',');
        Reader in = new FileReader(FILE_NAME);
        CSVParser parser = csvFormat.parse(in);
        List<CSVRecord> records = parser.getRecords();
        for (CSVRecord record : records) {
            String name = record.get("姓名");
            String age = record.get("年龄");
            String height = record.get("身高");
            String id = record.get("ID");
            String address = record.get("地址");
            System.out.println(record.toString());
            System.out.println(record.toString());
        }
        parser.close();
        in.close();
    }
}

打印如下:
CSVRecord [comment='null', recordNumber=1, values=[UZI, 23, 177, RNG-uzi, 中国]]
CSVRecord [comment='null', recordNumber=2, values=[Faker, 19, 178, hide on bush, 韩国]]
上一篇:上手 WebRTC DTLS 遇到很多 BUG?浅谈 DTLS Fragment


下一篇:.NET6新东西--struct优化