Spring Boot 导出 CSV 文件

Spring Boot CSV About 1,796 words

CSV

comma-separated values

后端代码

生成 CSV

bom是为了解决中文乱码问题。

public String generateContent(List<Trade> trades) {
    String header = String.join(",", "订单号", "手机号", "订单状态", "金额", "创建时间");
    String csv = trades.stream().map(trade -> {
        return String.join(",", trade.getTradeId(), trade.getPhoneNumber(), trade.getStatus(), trade.getPayAmount(), trade.getCreateTs());
    }).collect(Collectors.joining(System.lineSeparator()));
    String bom = new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
    return bom.concat(header).concat(System.lineSeparator()).concat(csv);
}

输出流

使用OutputStreamWriter包装,否则中文会乱码。

@GetMapping("/api/export")
public HttpServletResponse export(HttpServletResponse response) throws IOException {
    String csv = generateContent(...);
    try (OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) {
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("Content-Disposition", "attachment;filename=file.csv");
        writer.write(csv);
        writer.flush();
    }
    return response;
}

前端代码

a 标签

对于没有Authorization等自定义Header的下载导出,可以使用<a href=""></a>标签。

axios

function exportCsv() {
  http.get("/api/export", {
    params: {
    },
    responseType: 'blob'
  }).then((response) => {
    const blob = new Blob([response])
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = `订单明细_${Date.now()}.csv`; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  }).finally(() => {
  })
}
Views: 658 · Posted: 2024-05-29

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh