版本号org.apache.commons:commons-csv:1.9.0
package test;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Description 导出csv文件
* @Version 1.0
*/
public class Export {
private String exportCsv() {
String fileName = "导出csv";
String suffix = ".csv";
String pathName = "E:\\test" + fileName + suffix;
try {
OutputStream out = new FileOutputStream(pathName);
//防止乱码
byte[] bytes = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
out.write(bytes);
OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
CSVFormat csvFormat = CSVFormat.EXCEL.builder().setIgnoreHeaderCase(true).build();
CSVPrinter csvPrinter = new CSVPrinter(osw,csvFormat);
List<User> users = new ArrayList<>();
for (User user : users) {
csvPrinter.printRecord(
user.getNumber(),
user.getName());
}
csvPrinter.flush();
csvPrinter.close();
String uploadUrl = null;
File file = new File(pathName);
return uploadUrl;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}