package com.cccp.utils.tool;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
/**
* CSV工具类
*/
public class CsvUtil {
/**
* 导出CSV文件(写入到HTTP响应中)
*
* @param response HTTP相应
* @param fileName 文件名
* @param title 标题行(第一条)
* @param data 要插入的数据
* @param ignoreField 忽略的属性(不写入文件的字段)
* @param <T> 要写入的类型
* @throws Exception IO异常
*/
public static <T> void export(HttpServletResponse response, String fileName,
List<String> title, List<T> data, List<String> ignoreField) throws Exception {
export( response, fileName, title, data, ignoreField , new SimpleDateFormat("yyyyMMdd"));
}
/**
* 导出CSV文件(写入到HTTP响应中)
*
* @param response HTTP相应
* @param fileName 文件名
* @param title 标题行(第一条)
* @param data 要插入的数据
* @param ignoreField 忽略的属性(不写入文件的字段)
* @param <T> 要写入的类型
* @param sdf 日期格式化类型
* @throws Exception IO异常
*/
public static <T> void export(HttpServletResponse response, String fileName,
List<String> title, List<T> data, List<String> ignoreField, SimpleDateFormat sdf) throws Exception {
if (data == null) {
data = new ArrayList<>();
}
if (CollectionUtils.isEmpty(title)) {
// 标题和数据不能同时为空
if (data.isEmpty()) {
throw new Exception("标题和数据不能同时为空!");
}
// 如果标题为空则获取数据类型的字段名
title = getTitleByField(data.get(0).getClass(), ignoreField);
}
// 转换数据形式
List<List<String>> values = new LinkedList<>();
data.forEach(d -> values.add(getValues(d, ignoreField,sdf)));
// 导出为csv文件 开始
fileName += ".csv";
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "GBK");
BufferedWriter csvWriter = new BufferedWriter(writer, 1024);
response.reset();
// 设置返回头
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
// 写标题行
writeRow(title, csvWriter);
// 写数据
for (List<String> value : values) {
writeRow(value, csvWriter);
}
csvWriter.close();
writer.close();
}
/**
* 根据Class获取字段列表
*
* @param clazz 要获取字段的类
* @return 字段名
*/
public static List<String> getTitleByField(Class<?> clazz, List<String> ignoreField) {
Field[] fields = clazz.getDeclaredFields();
List<String> titleList = new ArrayList<>();
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField.contains(field.getName())) {
// 如果是忽略字段则跳过
continue;
}
titleList.add(field.getName());
}
return titleList;
}
/**
* 获取实体类的所有字段值
*
* @param object 要获取的对象
* @return 字符串形式的字段值
*/
private static List<String> getValues(Object object, List<String> ignoreField,SimpleDateFormat sdf) {
List<String> ret = new LinkedList<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField.contains(field.getName())) {
// 忽略字段跳过
continue;
}
Object value;
try {
value = field.get(object);
} catch (Exception e) {
value = null;
}
String val;
if (value instanceof Date) {
// 如果是日期 则格式化
val = sdf.format((Date) value);
} else {
val = value == null ? "" : value.toString();
}
ret.add(val);
}
return ret;
}
/**
* 写一行数据
*
* @param str 数据数组
* @param csvWriter 写入缓存
* @throws IOException IO异常
*/
private static void writeRow(List<String> str, BufferedWriter csvWriter) throws IOException {
// 写入
/* for (String data : str) {
if (data == null || "null".equals(data)) {
csvWriter.write(",");
} else {
csvWriter.write(data + ",");
}
}*/
for (int i = 0; i < str.size(); i++) {
String data = str.get(i);
if (data == null || "null".equals(data)) {
csvWriter.write(",");
} else {
if (i == str.size()-1) {
csvWriter.write(data);
}else {
csvWriter.write(data + ",");
}
}
}
csvWriter.newLine();
}
}
标签:csvWriter,List,param,ignoreField,import,工具,csv,data
From: https://www.cnblogs.com/lkyzhengyj/p/18291623