Java导出CSV文件

以前导出总是用POI导出为Excel文件,后来当我了解到CSV以后,我发现速度飞快。如果导出的数据不要求格式、样式、公式等等,建议最好导成CSV文件,因为真的很快。虽然我们可以用Java再带的文件相关的类去操作以生成一个CSV文件,但事实上有好多第三方类库也提供了类似的功能。
这里我们使用apache提供的commons-csv组件。

一、加入pom

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

二、例子

1、写csv
 public static  void writerCSVFile(String path,List<String> headList,  List<List<String>> dataList) throws Exception{
        FileOutputStream fos = new FileOutputStream(path);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headList.toArray(new String[0]));
        CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
        for(List<String> data:dataList){
            csvPrinter.printRecord(data.toArray());
        }
        csvPrinter.flush();
        csvPrinter.close();
    }

测试:

 public static void main(String[] args) throws Exception {
        ArrayList<String> strings = Lists.newArrayList("姓名", "年龄", "性别");
        List<List<String>> dataList=new ArrayList<>();
        for(int i=0;i<5;i++){
            dataList.add(Lists.newArrayList("张三"+i, "10", "男"));
        }
        writerCSVFile("D:/3333.csv", strings,dataList);
    }

结果:
image.png

2、读csv
 public static List<CSVRecord> readCSV(String path) throws Exception{
        InputStream is = new FileInputStream(path);
        InputStreamReader isr = new InputStreamReader(is, "GBK");
        Reader reader = new BufferedReader(isr);
        CSVParser parser = CSVFormat.EXCEL.parse(reader);
        List<CSVRecord> list = parser.getRecords();
        parser.close();
        return list;
    }

测试:

public static void main(String[] args) throws Exception {
        List<CSVRecord> list=  readCSV("D:/3333.csv");
        System.out.println(list);
    }

结果:
image.png

# 开发使用  

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×