JAVA List(或者数据库数据集合)导出为CSV
程序员文章站
2024-03-20 21:27:16
...
1、build.gradle配置
compile group: 'net.sourceforge.javacsv', name: 'javacsv', version: '2.0'
2、代码实例
//添加数据,添加完数据后,把这条数据保存到csv文件
public MaintenanceRecordDTO addRecord(MaintenanceRecordQuery record) {
try {
recordDao.insertSelective(createDO(record));
} catch (DuplicateKeyException e) {
recordDao.updateByPrimaryKeySelective(createDO(record));
}
ResMaintenanceRecord data = recordDao.selectByPrimaryKey(createDO(record));
//文件路径
String csvFilePath = "D://" + data.getMaintenanceRecordId() + ".csv";
//保存的数据
List<ResMaintenanceRecord> list = new ArrayList<>();
list.add(data);
//反射获取类属性,用于csv的表头
Field[] fields = data.getClass().getDeclaredFields();
String[] csvHeaders = new String[fields.length];
for (short i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
csvHeaders[i] = fieldName;
}
writeCSV(list, csvFilePath, csvHeaders);
return createDTO(data);
}
public static <T> void writeCSV(Collection<T> dataSet, String csvFilePath, String[] csvHeaders) {
try {
//判断文件是否存在,存在则删除,然后创建新表格
File tmp = new File(csvFilePath);
if (tmp.exists()) {
if (tmp.delete()) {
//logger.info(csvFilePath + Constant.DUPLICATE_FILE_DELETE);
}
}
//定义路径,分隔符,编码
CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));
//写表头
csvWriter.writeRecord(csvHeaders);
//遍历集合 写内容
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();
// 报错:因为get方法是private,所以不能访问
//String textValue = field.get(t).toString();
csvContent[i] = textValue;
} catch (Exception e) {
e.getStackTrace();
}
}
//迭代插入记录
csvWriter.writeRecord(csvContent);
}
csvWriter.close();
System.out.println("<--------CSV文件写入成功-------->");
} catch (IOException e) {
e.printStackTrace();
throw new RequestResultErrorException("请先关闭已经打开的文件!");
}
}
参考
https://blog.csdn.net/qq593467574/article/details/78124954
https://www.jb51.net/article/102607.htm
https://blog.csdn.net/loongshawn/article/details/53457953
上一篇: 从闭包引出来的一系列问题
下一篇: JS判断两个时间戳是否为同一天