在 React 项目里下载 CSV 文件常见有两种方式:
-
前端生成 CSV 并触发下载
适合数据在前端就已经有了。 -
从后端获取 CSV 并下载
适合后端导出 CSV,再返回给前端。
下面给你两种实现方式 👇
✅ 方式一:前端生成 CSV 文件并下载
// utils/downloadCsv.ts
export function downloadCsv(filename: string, rows: string[][]) {
// 将二维数组转换为 CSV 字符串
const csvContent =
"data:text/csv;charset=utf-8," +
rows.map((row) => row.map((item) => `"${item}"`).join(",")).join("\n");
// 创建隐藏的 <a> 标签触发下载
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
在组件里使用:
import React from "react";
import { downloadCsv } from "./utils/downloadCsv";
const ExportButton: React.FC = () => {
const handleExport = () => {
const data = [
["Name", "Age", "Email"],
["Alice", "24", "alice@example.com"],
["Bob", "30", "bob@example.com"],
];
downloadCsv("users.csv", data);
};
return <button onClick={handleExport}>Download CSV</button>;
};
export default ExportButton;
✅ 方式二:从后端获取 CSV 并下载
如果后端返回的是 文件流 (blob),可以这样处理:
import React from "react";
const ExportButton: React.FC = () => {
const handleDownload = async () => {
const response = await fetch("/api/export-csv", {
method: "GET",
});
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
};
return <button onClick={handleDownload}>Download CSV</button>;
};
export default ExportButton;
⚠️ 确保后端设置了正确的响应头,比如:
Content-Type: text/csv Content-Disposition: attachment; filename="data.csv"



667

被折叠的 条评论
为什么被折叠?



