// 添加super-csv依賴
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.4.0</version>
</dependency>
// 后端controller層
@RequestMapping(value = "/apps/boot-percentage", method = RequestMethod.GET)
public void bootPercentage(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/csv");
String current = new Date().toString().replace(" ", "-");
String filename = URLEncoder.encode("SpringBoot應用占比統(tǒng)計表-" + current + ".csv", GlobalConstants.UTF_8);
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
// 防止亂碼出現
Writer writer = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8);
// 寫入字節(jié)流畦粮,讓文檔以UTF-8編碼
writer.write('\uFEFF');
ICsvBeanWriter csvWriter = new CsvBeanWriter(writer, CsvPreference.STANDARD_PREFERENCE);
String[] header = {"groupName", "backEndSpringBootAppsTotal", "backEndAppsTotal", "springBootPercentage"};
csvWriter.writeHeader(header);
List<BootPercentageResp> bootPercentageList = appsService.bootPercentage(); // 這是一個業(yè)務代碼 返回我要導出去的數據
for (BootPercentageResp bootPercentage : bootPercentageList) {
csvWriter.write(bootPercentage, header);
}
csvWriter.close();
}
// 前端
<a href="/你寫的接口"></a>
官方文檔
http://super-csv.github.io/super-csv/examples_writing.html
Q1: 沒有中文標題
/*
本來csv就是以 挫以,進行分割單元格 csvWriter.writeComment(""); 這個可以寫入行
文檔地址:[http://super-csv.github.io/super-csv/apidocs/index.html](http://super-csv.github.io/super-csv/apidocs/index.html)
*/
Map<String, List<UpgradeInfoResp>> upgradeInfoList = appsService.upgradeInfo();
for (String groupName : upgradeInfoList.keySet()) {
csvWriter.writeComment(groupName);
csvWriter.writeComment("應用名稱,上線時間");
for (UpgradeInfoResp upgradeInfoResp : upgradeInfoList.get(groupName)) {
csvWriter.write(upgradeInfoResp, header);
}
csvWriter.writeComment("");
}
Q2: 沒有好看的間距