网上有很多教程,都是什么乱七八糟的。还是自己写的舒服
/**
* @param path 路径
* @param fileName 文件名
* @param headList 表头列表
* @param dataList 数据列表
*/
public static void createCSV(String path, String fileName, List<String> headList, List<List<String>> dataList) {
try {
fileName = path + fileName + EXT_CSV;
File file = new File(fileName);
if (Objects.nonNull(file.getParentFile()) && !file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()){
log.info("file create fail! | {}", fileName);
}
}
FileOutputStream fos;
CSVFormat csvFormat;
if (file.exists()) {
fos = new FileOutputStream(file, true);
csvFormat = CSVFormat.DEFAULT;
} else {
if (!file.createNewFile()){
log.info("file create fail! | {}", fileName);
}
fos = new FileOutputStream(file);
String[] headArray = headList.toArray(new String[0]);
csvFormat = CSVFormat.DEFAULT.withHeader(headArray).withAllowDuplicateHeaderNames();
}
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
for (List<String> data : dataList) {
csvPrinter.printRecord(data);
}
csvPrinter.flush();
csvPrinter.close();
} catch (Exception e) {
log.info("导出CSV文件失败 fileName {}", fileName);
}
}