以前导出总是用POI导出为Excel文件,后来当我了解到CSV以后,我发现速度飞快。如果导出的数据不要求格式、样式、公式等等,建议最好导成CSV文件,因为真的很快。虽然我们可以用Java自带的文件相关的类去操作以生成一个CSV文件,但事实上有好多第三方类库也提供了类似的功能。
这里我们使用apache提供的commons-csv组件。
一、加入pom
<dependency><groupId>org.apache.commonsgroupId><artifactId>commons-csvartifactId><version>1.5version>dependency>
二、例子
1、写csv
public static void writerCSVFile(String path,List headList, List> 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 data:dataList){csvPrinter.printRecord(data.toArray());}csvPrinter.flush();csvPrinter.close();}
测试:
public static void main(String[] args) throws Exception {ArrayList strings = Lists.newArrayList("姓名", "年龄", "性别");List> dataList=new ArrayList<>();for(int i=0;i<5;i++){dataList.add(Lists.newArrayList("张三"+i, "10", "男"));}writerCSVFile("D:/3333.csv", strings,dataList);}
结果:
2、读csv
public static ListreadCSV(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 list = parser.getRecords();parser.close();return list;}
测试:
public static void main(String[] args) throws Exception {List list= readCSV("D:/3333.csv");System.out.println(list);}
结果: