以前导出总是用POI导出为Excel文件,后来当我了解到CSV以后,我发现速度飞快。
如果导出的数据不要求格式、样式、公式等等,建议最好导成CSV文件,因为真的很快。
虽然我们可以用Java再带的文件相关的类去操作以生成一个CSV文件,但事实上有好多第三方类库也提供了类似的功能。
这里我们使用apache提供的commons-csv组件
Commons CSV
文档在这里
http://commons.apache.org/
http://commons.apache.org/proper/commons-csv/
http://commons.apache.org/proper/commons-csv/user-guide.html
先看一下具体用法
@Test public void testWrite() throws Exception {
FileOutputStream fos = new FileOutputStream("E:/cjsworkspace/cjs-excel-demo/target/abc.csv");
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("姓名", "年龄", "家乡");
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);// csvPrinter = CSVFormat.DEFAULT.withHeader("姓名", "年龄", "家乡").print(osw);
for (int i = 0; i < 10; i++) {
csvPrinter.printRecord("张三", 20, "湖北");
}
csvPrinter.flush();
csvPrinter.close();
}
@Test public void testRead() throws IOException {
InputStream is = new FileInputStream("E:/cjsworks