public void exportSomeCsv(List<ProbeLogEntity> list, String csvName, List<SysFiledExportTaskDto> exportSignals) throws Exception {
for (int i = 0; i < list.size(); i++) {
ProbeLogEntity probeLogEntity = list.get(i);
probeLogEntity.getVin();
}
List<Map<String, Object>> records = new ArrayList<>();
Map<String, Object> maptest1 = new HashMap<>();
Map<String, Object> maptest2 = new HashMap<>();
Map<String, Object> maptest3 = new HashMap<>();
maptest1.put("字段1", "你");
maptest1.put("字段2", "好");
maptest2.put("字段1", "你你");
maptest2.put("字段2", "好好");
maptest3.put("字段1", "你你你");
maptest3.put("字段2", "好好好");
records.add(maptest1);
records.add(maptest2);
records.add(maptest3);
FileOutputStream fos = new FileOutputStream(csvName);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
byte[] uft8bom = {(byte) 0xef, (byte) 0xbb, (byte) 0xbf};
fos.write(uft8bom);
Map<String, String> fieldHeaderMap = new HashMap<>();
String[] headerArr = new String[]{"这是啥", "字段1", "字段2"};
fieldHeaderMap.keySet().toArray(headerArr);
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headerArr);
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
Map<String, Object> temp = new LinkedHashMap<>();
for (Map<String, Object> record : records) {
for (String s : headerArr) {
temp.put(s, record.get(s));
}
csvPrinter.printRecord(temp.values());
temp.clear();
}
csvPrinter.flush();
csvPrinter.close();
}
public static <T> void writeCSV(Collection<T> dataSet, String csvFilePath, String[] csvHeaders) {
try {
File tmp = new File(csvFilePath);
if (tmp.exists()) {
if (tmp.delete()) {
}
}
FileOutputStream fos = new FileOutputStream(csvFilePath);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
byte[] uft8bom = {(byte) 0xef, (byte) 0xbb, (byte) 0xbf};
fos.write(uft8bom);
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(csvHeaders);
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
Iterator<T> it = dataSet.iterator();
while (it.hasNext()) {
T t = (T) it.next();
Field[] fields = t.getClass().getDeclaredFields();
String[] csvContent = new String[fields.length];
for (short i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
Object value = getMethod.invoke(t, new Object[]{});
if (value == null) {
continue;
}
String textValue = value.toString();
csvContent[i] = textValue;
} catch (Exception e) {
e.getStackTrace();
}
}
csvPrinter.printRecord(csvContent);
}
csvPrinter.close();
System.out.println("<--------CSV文件写入成功-------->");
} catch (IOException e) {
e.printStackTrace();
}
}