Java生成csv
List<Map<String, Object>> list, LinkedHashMap<String, Object> titleMap
titleMap的k值和value值一样
titleMap的k值对应List<Map<String, Object>中的k值表示与标题栏对应
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import com.dtroad.ieasweb.util.StrUtil;
import java.io.File;
import java.util.*;
/**
* author ss
* createTime 2020/4/23
* package
* desc 生成csv文件
***/
public class CsvBigExportUtil {
public static Map<String, Object> export(List<Map<String, Object>> list, LinkedHashMap<String, Object> titleMap, String Path, String fileName) {
String filePath = Path + "/" + fileName;
CsvWriter writer = CsvUtil.getWriter(filePath, CharsetUtil.CHARSET_UTF_8);
//构建csv头部
String[] head = new String[titleMap.size()];
Iterator<Map.Entry<String, Object>> headEntries = titleMap.entrySet().iterator();
int h = 0;
while (headEntries.hasNext()) {
Map.Entry<String, Object> entry = headEntries.next();
Object value = entry.getValue();
head[h] = value.toString();
h++;
}
//先写入头部栏目再写入栏目内容,大批量随便导出
//获取列表中数据必须是按照列表的数据必须对应头部栏目
writer.write(head);
//根据titleMap的key值去获取
for (int i = 0; i < list.size(); i++) {
Map map = list.get(i);
String[] content = new String[map.size()];
int j = 0;
Iterator<Map.Entry<String, Object>> tempHead = titleMap.entrySet().iterator();
while (tempHead.hasNext()) {
Map.Entry<String, Object> entry = tempHead.next();
String key = entry.getKey();
content[j] = "" + StrUtil.toString(map.get(key)) + "";
j++;
}
writer.write(content);
}
writer.close();
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("file", new File(filePth));
resultMap.put("path", filePth);
return resultMap;
}
}