一、核心思路
- 把 JS 数组拼成「逗号分隔 + 换行」的字符串 → 这就是 CSV 的"文本协议"。
- 利用 Blob 把字符串变成文件流。
- 创建一个看不见的
<a>标签,给它一个download属性,再自动点一下,浏览器就会弹出保存框。
二、核心代码
1. 准备原始数据
原始数据可以是接口返回,也可以是 mock。
js
const posts = [
{ id:1, title:'用 Vite 搭建 React 18 项目', link:'...', img:'...', views:12034 },
// ...
];
2. 定义表头
顺序随意,只要和下面 map 对应即可。
js
const headers = ['id','名称','链接','图片','阅读'];
3. 拼接数据
js
const csvContent = [
headers.join(','), // 第一行:表头
...posts.map(item => [ // 剩余行:数据
`"${item.id}"`,
`"${item.title}"`,
`"${item.link}"`,
`"${item.img}"`,
`"${item.views}"`
].join(','))
].join('\n');
4. 生成文件并下载
js
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.href = url;
link.download = `文章信息_${new Date().toISOString()}.csv`;
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
三、完整代码
js
// 1. 造点假数据
const posts = [
{
id: 1,
title: '用 Vite 搭建 React 18 项目',
link: 'https://example.com/vite-react18',
img: 'https://example.com/cover/vite-react.jpg',
views: 12034
},
{
id: 2,
title: 'Tailwind CSS 3 响应式布局技巧',
link: 'https://example.com/tailwind-layout',
img: 'https://example.com/cover/tailwind.jpg',
views: 8721
},
{
id: 3,
title: '深入浅出浏览器事件循环',
link: 'https://example.com/event-loop',
img: 'https://example.com/cover/event-loop.jpg',
views: 15003
},
{
id: 4,
title: 'Webpack 5 性能优化清单',
link: 'https://example.com/webpack5-optimize',
img: 'https://example.com/cover/webpack.jpg',
views: 9855
},
{
id: 5,
title: '前端图片懒加载完整方案',
link: 'https://example.com/lazy-load',
img: 'https://example.com/cover/lazy-load.jpg',
views: 6542
}
];
// 2. 组装 CSV
const headers = ['id', '名称', '链接', '图片', '阅读'];
const csvContent = [
headers.join(','),
...posts.map(item => [
`"${item.id}"`,
`"${item.title}"`,
`"${item.link}"`,
`"${item.img}"`,
`"${item.views}"`
].join(','))
].join('\n');
// 3. 下载
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', `文章信息_${new Date().toISOString()}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url); // 释放内存
快速体验
- 打开任意网页,F12 进控制台
- 把完整代码全部粘进去,回车