https://www.cnblogs.com/shengluBlog/p/13176321.html
阅读
使用common-csv
实践内容:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.9.0</version>
</dependency>
util
package com.cicc.***.util;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
public class CsvUtil {
/**
* 生成csv文件
*
* @param headers csv文件头部信息
* @param outputWay 输出地址
* @param data 填充数据
* @throws IOException
*/
public static void generateCsvFile(List<String> headers, String outputWay, List<List<Object>> data) throws IOException {
try (FileOutputStream fos = new FileOutputStream(outputWay);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK")) {
String[] toBeStored = headers.toArray(new String[headers.size()]);
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(toBeStored);
try (CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat)) {
for (int i = 0; i < data.size(); i++) {
List<Object> singleData = data.get(i);
csvPrinter.printRecord(singleData);
}
csvPrinter.flush();
}
} catch (Exception e) {
throw e;
}
}
/**
* 写出csv文件流
*
* @param response
* @param inputWay
*/
public static void exportCsvFile(HttpServletResponse response, String inputWay, String fileName) throws IOException {
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
File fileLoad = new File(inputWay);
response.reset();
response.setContentType("application/csv");
response.setHeader("content-disposition", "attachment;filename=" + new String((fileName + ".csv").getBytes()));
long fileLength = fileLoad.length();
String length1 = String.valueOf(fileLength);
response.setHeader("Content_Length", length1);
try (FileInputStream in = new FileInputStream(fileLoad)) {
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
}
out.close();
// 删除临时文件
fileLoad.delete();
}
}
service
List<VO> list = 查询数据列表;
List<List<Object>> csvDatas = new ArrayList<>();
for (VO vo: list) {
//数据处理
csvDatas.add(eddiVO);
}
String[] headers = new String[]{"c1", "c2", "c3"};
List<String> headerList = Arrays.asList(headers);
try {
String tempDir = System.getProperty("java.io.tmpdir")+ File.separator + "filename.csv";
CsvUtil.generateCsvFile(headerList, tempDir, csvDatas);
CsvUtil.exportCsvFile(response, tempDir, "filename");
} catch (Exception e) {
log.error("export error:", e)
//抛出异常
}
使用open-csv
https://stackabuse.com/reading-and-writing-csvs-in-java-with-opencsv/