java apache commons-csv导出,浏览器下载

以前导出总是用POI导出为Excel文件,但是如果单个字段的数据特量长时,会把excel撑爆的(具异常忘记了,大概意思就是超出的excel单元格的最大长度)。经查询了解到CSV,而且比excel速度快,效率高。
如果导出的数据不要求格式、样式、公式等等,建议最好导成CSV文件,因为真的很快。
虽然我们可以用Java再带的文件相关的类去操作以生成一个CSV文件,但事实上有好多第三方类库也提供了类似的功能。

apachecommons-csv 组件

这里我们使用 apache 提供的 commons-csv 组件
commons-csv 由两大核心对象组成 CSVParser(解析),CSVPrinter(写csv)。

参考文档:
http://commons.apache.org/
http://commons.apache.org/proper/commons-csv/
http://commons.apache.org/proper/commons-csv/user-guide.html

依赖:

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

工具类:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

/**
 * csv导出工具类
 */
public class CommonsCsvUtil {

	public static void main(String[] args) throws Exception {

		List<String> headerList = new ArrayList<>(Arrays.asList("时间", "问题", "意图", "意图Data"));
		List<List<String>> dataList = new ArrayList<>();

		for (int i = 0; i < 10; i++) {
			List<String> rowList = new ArrayList<String>();
			rowList.add("张  三_"+i);
			rowList.add("2 ,./  0 _"+i);
			rowList.add("Gold_getPrice _"+i);
			rowList.add("mmons-csv,  由两大核心对象组成 ,CSVParser.(解析),CSVPrinter(写csv),");
			dataList.add(rowList);
		}

		String[] headers = new String[headerList.size()];
		headerList.toArray(headers);
		exportByList(headers, dataList);
		
		System.out.println("=======结束==========");
	}

	public static void exportByList(String[] headers, List<List<String>> dataList) throws FileNotFoundException {
		FileOutputStream fileos = new FileOutputStream("E:/abc.csv");
		exportByList(headers, dataList, fileos);
	}

	public static void exportByList(String[] headers, List<List<String>> dataList, OutputStream os) {
		OutputStreamWriter osw = null;
		CSVFormat csvFormat = null;
		CSVPrinter csvPrinter = null;
		try {
			osw = new OutputStreamWriter(os, "GBK");//如果是UTF-8时,WPS打开是正常显示,而微软的excel打开是乱码,
			csvFormat = CSVFormat.DEFAULT.withHeader(headers);
			csvPrinter = new CSVPrinter(osw, csvFormat);
			for (int i = 0; i < dataList.size(); i++) {
				List<String> values = dataList.get(i);
				csvPrinter.printRecord(values);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(os, csvPrinter);
		}
	}

	public static void exportByLinked(String[] headers, List<LinkedHashMap<String, Object>> dataList)
			throws FileNotFoundException {
		FileOutputStream fileos = new FileOutputStream("E:/abc.csv");
		exportByLinked(headers, dataList, fileos);
	}

	public static void exportByLinked(String[] headers, List<LinkedHashMap<String, Object>> dataList, OutputStream os) {
		OutputStreamWriter osw = null;
		CSVFormat csvFormat = null;
		CSVPrinter csvPrinter = null;
		try {

			osw = new OutputStreamWriter(os, "GBK");
			csvFormat = CSVFormat.DEFAULT.withHeader(headers);
			csvPrinter = new CSVPrinter(osw, csvFormat);

			for (int i = 0; i < dataList.size(); i++) {
				List<String> values = new ArrayList<String>();
				LinkedHashMap<String, Object> rowHashMap = dataList.get(i);
				Set<String> keys = rowHashMap.keySet();
				for (String key : keys) {
					values.add(String.valueOf(rowHashMap.get(key)));
				}
				csvPrinter.printRecord(values);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(os, csvPrinter);
		}
	}

	private static void close(OutputStream os, CSVPrinter csvPrinter) {
		if (csvPrinter != null) {
			try {
				csvPrinter.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				csvPrinter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (os != null) {
			try {
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Controller层:(伪代码)

@Controller
public class ChatController {

	@RequestMapping(value = "/exportCsv")
	public void  exportCsv(HttpServletResponse response) throws Exception {	
		List<List<String>> dataList = new LinkedList<>();		
		String filename = "xxx.csv";
		response.reset();
		filename = new String(filename.getBytes("UTF-8"), "iso8859-1");
		response.addHeader("Content-Disposition", "attachment;filename=" + filename);
		response.setContentType("multipart/form-data");
		OutputStream os = response.getOutputStream();// 取得输出流
		String[] headers=new String[]{"aa","bb","cc","dd"};
			
		CommonsCsvUtil.exportByList(headers, dataList,os);
		
		if(os!=null){
			os.flush();
			os.close();
		}
	}

}
相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页