将List<Map<String, Object>>封装成csv文件
时间: 2024-03-13 08:39:28 浏览: 22
可以使用Apache Commons CSV库将List<Map<String, Object>>封装成CSV文件。以下是一个示例代码:
```java
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class CsvWriter {
public static void writeListMapToCsv(List<Map<String, Object>> data, String filePath) throws IOException {
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(filePath), CSVFormat.DEFAULT)) {
// 写入CSV文件的表头
if (!data.isEmpty()) {
Map<String, Object> firstRow = data.get(0);
csvPrinter.printRecord(firstRow.keySet());
}
// 写入数据行
for (Map<String, Object> row : data) {
csvPrinter.printRecord(row.values());
}
csvPrinter.flush();
}
}
}
```
使用上述代码,你可以将List<Map<String, Object>>中的数据封装成CSV文件。你需要提供一个文件路径作为参数,该文件路径将用于保存生成的CSV文件。请确保在使用代码之前已经添加了Apache Commons CSV库的依赖。