Excel可能会有一系列公式,格式等,csv时纯文本文档。可以理解csv是可以被excel打开的纯文本文档。csv占用资源较少,速度更快。
# 要导出的内容
List<Person> lines = Arrays.asList(new Person());
# 构造到导出到哪里
String fileName = FileIUtils.genFileName("D:\\projects\\", lines.get(0).getClass().getSimpleName(), ".csv");
# 构造csv的文件内容
String str = buildCsvFileTable(lines);
# 执行导出
FileIUtils.writeFile2(fileName, str);
// 生成文件名字
public static String genFileName(String path, String name, String suffix) {
String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HHMMSS"));
return path + "/" + name + time + suffix;
}
public static String buildCsvFileTable(List dataList) {
Map<String, Object> map = ReflectUtils.beanToMap(dataList.get(0));
List<Map<String, Object>> mapList = new ArrayList<>();
for (Object o : dataList) {
mapList.add(ReflectUtils.beanToMap(o));
}
// 构建excel 标题行名
StringBuilder lineBuilder = new StringBuilder();
for (String key : map.keySet()) {
lineBuilder.append(key).append(",");
}
lineBuilder.append(System.lineSeparator());
// 构建excel内容
for (Map<String, Object> rowData : mapList) {
for (Object value : rowData.values()) {
if (Objects.nonNull(value)) {
lineBuilder.append(value).append(",");
} else {
lineBuilder.append("--").append(",");
}
}
lineBuilder.append(System.lineSeparator());
}
return lineBuilder.toString();
}
// 写文件 try=with-resources
public static void writeFile(String fileName, String content) {
try (FileOutputStream fos = new FileOutputStream(fileName, true);
OutputStreamWriter writer = new OutputStreamWriter(fos, "GBK")) {
writer.write(content);
writer.flush();
} catch (Exception e) {
System.out.println("写文件异常" + e);
}
}