/**
* @param response 响应流
* @param fields
* @param dataList 数据源
*/
private static void writeCSV(HttpServletResponse response, List<SqlFieldVO> fields, List<Map<String, Object>> dataList) {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = "SQLResult" + df.format(new Date()) + ".csv";
OutputStream out = null;
CSVWriter writer = null;
try {
// 设置响应头,指定文件类型为CSV
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 创建CSVWriter对象 将其连接到响应的OutputStream
out = response.getOutputStream();
out.write(new byte []{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
writer = new CSVWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
// 写入表头
String[] header = fields.stream().map(vo -> {
String name = vo.getFieldCode();
if (vo.getFieldTitle() != null && !Objects.equals(vo.getFieldTitle(), "")) {
name = vo.getFieldTitle();
}
return name;
}).toArray(String[]::new);
writer.writeNext(header);
// 写入数据
for (Map<String, Object> map : dataList) {
List<String> tempList = new ArrayList<>();
fields.stream().forEach(field ->{
tempList.add(map.get(field.getFieldCode()) == null ? "" : map.get(field.getFieldCode()).toString());
});
writer.writeNext(tempList.toArray(new String[0]));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (writer != null){
try {
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (out != null){
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
06-15
195