csv 导出工具
一般大数据量导出 都会选择 csv 格式,就是存文本格式,相比excel 轻量级,同样数据量 csv 文件更小。
工具类,分页导出
/**
* Author: lyc
* Date: 2024/07/05 16:27
*/
@Slf4j
public class CsvUtils {
/**
* 大数量导出
*
* @param fileName 生成文件地址
* @param clazz 类
* @param pages 总页数
* @param function 获取数据函数
* @return
*/
public static String exportCsv(String fileName, Class clazz, long pages, Function<Integer, List<?>> function) {
//指定路径和编码
CsvWriter writer = CsvUtil.getWriter(fileName, CharsetUtil.CHARSET_UTF_8);
Field[] fields = ReflectUtil.getFields(clazz);
String[] headerArray = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
headerArray[i] = Optional.ofNullable(field.getAnnotation(Alias.class))
.map(alias -> alias.value())
.orElse(field.getName()
);
}
writer.write(headerArray);
//按行写出
for (int i = 1; i <= pages; i++) {
List list = function.apply(i);
writeStringArray(list, clazz, writer);
}
return fileName;
}
/**
* 字符串数组 写入
*
* @param list
* @return
*/
private static void writeStringArray(List list, Class clazz, CsvWriter writer) {
for (int i = 0; i < list.size(); i++) {
Field[] fields = ReflectUtil.getFields(clazz);
Object o = list.get(i);
String[] array = new String[fields.length];
for (int j = 0; j < fields.length; j++) {
Field field = fields[j];
Object fieldValue = ReflectUtil.getFieldValue(o, field);
array[j] = Optional.ofNullable(fieldValue)
.map(value -> formatStr(value))
.orElse("");
}
writer.write(array);
}
}
/**
* 格式化数据
* @param value
* @return
*/
private static String formatStr(Object value){
if(null == value){
return "";
}
if(value instanceof LocalDateTime){
LocalDateTime dateTime = (LocalDateTime) value;
return DateUtils.getDateTimeStr(dateTime);
}
if(value instanceof LocalDate){
LocalDate localDate = (LocalDate) value;
return DateUtils.getDateStr(localDate);
}
return String.valueOf(value);
}
}
使用 类上加注解
@Alias("活动名称")
private String name;
String fileName = "e:/testWrite00101.csv";
Integer size = 10;
CsvUtils.exportCsv(fileName, AdminSpecsActivityVO.class,3,(j) -> {
AdminSpecsActivityQuery adminSpecsActivityQuery = new AdminSpecsActivityQuery();
adminSpecsActivityQuery.setPageNum(j);
adminSpecsActivityQuery.setPageSize(size);
PageVO pageVO = adminSpecsActivityService.page(adminSpecsActivityQuery);
return pageVO.getList();
});