com.yuweix.kuafu.core.csv.CsvUtil Maven / Gradle / Ivy
The newest version!
package com.yuweix.kuafu.core.csv;
import java.beans.PropertyDescriptor;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import jakarta.servlet.http.HttpServletResponse;
/**
* @author yuwei
*/
public abstract class CsvUtil {
private static final Logger log = LoggerFactory.getLogger(CsvUtil.class);
/**
* 导出数据
* @param dataList 数据
*/
public static byte[] export(List dataList) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
export(dataList, out);
byte[] data = out.toByteArray();
try {
out.close();
} catch (IOException e) {
log.error("", e);
}
return data;
}
public static void export(List dataList, HttpServletResponse response, String fileName) {
response.setContentType("application/csv");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.setHeader("_filename", fileName);
response.setHeader("Access-Control-Expose-Headers", "_filename");
try {
export(dataList, response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 导出数据到输出流
* @param dataList 数据
*/
public static void export(List dataList, OutputStream out) {
log.info("list size: {}", dataList == null ? 0 : dataList.size());
if (dataList == null || dataList.size() <= 0) {
return;
}
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
//追加BOM标识,防止Excel打开时乱码
out.write(0xef);
out.write(0xbb);
out.write(0xbf);
osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
bw = new BufferedWriter(osw);
/**
* 输出头部
**/
List headList = getOutputHeadList(dataList.get(0));
for (String head: headList) {
bw.append(head).append(",");
}
bw.newLine();
List keyList = getOutputKeyList(dataList.get(0));
/**
* 输出数据部分
**/
for (T t: dataList) {
List