12-Java读写CSV格式文件(opencsv)

时间:2021-05-16 10:02:05

使用opencsv(opencsv-2.3.jar),下载地址:http://sourceforge.net/projects/opencsv/files/latest/download

maven依赖

<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
    <groupId>net.sourceforge.javacsv</groupId>
    <artifactId>javacsv</artifactId>
    <version>2.1</version>
</dependency>

API 说明文档:http://javacsv.sourceforge.net/
很重要:http://javacsv.sourceforge.net/com/csvreader/CsvWriter.html

一,读取CSV格式文件:

import java.io.File;  
import java.io.FileReader;  
import java.util.List;  

import au.com.bytecode.opencsv.CSVReader;  

public class ReadCSV {  
    public static void main(String[] args) throws Exception {  
        File file = new File("e:\\read.csv");  
        FileReader fReader = new FileReader(file);  
        CSVReader csvReader = new CSVReader(fReader);  
        String[] strs = csvReader.readNext();  
        if(strs != null && strs.length > 0){  
            for(String str : strs)  
                if(null != str && !str.equals(""))  
                    System.out.print(str + " , ");  
            System.out.println("\n---------------");  
        }  
        List<String[]> list = csvReader.readAll();  
        for(String[] ss : list){  
            for(String s : ss)  
                if(null != s && !s.equals(""))  
                    System.out.print(s + " , ");  
            System.out.println();  
        }  
        csvReader.close();  
    }  
}  

执行结果如下:

编号 , 姓名 , 备注 ,   
--------------- 1 , Li , 123456 ,   
2 , Sean ,   

二,写CSV格式文件:

public static void write(){

        String filePath = "/Users/dddd/test.csv";

        try {
            // 创建CSV写对象
            CsvWriter csvWriter = new CsvWriter(filePath,',', Charset.forName("GBK"));
            //CsvWriter csvWriter = new CsvWriter(filePath);

            // 写表头
            String[] headers = {"编号","姓名","年龄"};
            String[] content = {"12365","张山","34"};
            csvWriter.writeRecord(headers);
            csvWriter.writeRecord(content);
            csvWriter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }