controller
@PostMapping(value = "/exportCsv")
public ResponseEntity<byte[]> exportCsv() {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=fileName.csv");
headers.setContentType(MediaType.valueOf("application/csv;charset=GBK"));
return new ResponseEntity<>(service.exportCsv(), headers, HttpStatus.OK);
}
service
public byte[] exportCsv() {
// 准备数据
return doExport(colNames, dataList, fields).toByteArray();
}
//Constants.COMMA =",”;
private doExport(String[] colNames, List<JSONObject> dataList, List<String> fields) {
StringBuilder buf = new StringBuilder();
// 列名
for (String colName : colNames) {
buf.append(colName).append(Constants.COMMA);
}
buf.append("\r\n");
// 数据
if (null != fundList) {
for (JSONObject data : dataList) {
for (String field : fields) {
buf.append(data.get(field, "")).append(Constants.COMMA);
}
}
buf.append("\r\n");
}
}
// 响应
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
os.write(buf.toString().getBytes("GBK"));
os.flush();
return os;
} catch (Exception e) {
log.error("doExport错误...", e);
e.printStackTrace();
}
return new ByteArrayOutputStream();
}
附:
1.csv分隔符【,】,xls分隔符【tab】
2.用Excel默认方式打开UTF-8编码的csv乱码,所以采用GBK编码