说明
- 没有用到后端nodejs,就是纯前端js实现
- 表格类型是
.csv (直接改后缀变成.xlsx 文件) - 下面的代码包括自己封装的函数和例子,直接复制下面的代码可以用。
代码和样例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>下载SCV文件</title>
</head>
<body>
<button id="btn">下载</button>
</body>
<script>
function downScv(fileName, data){
let scv_header = ""
for(let header in data[0]){
scv_header += `${header},`
}
let scv = `${scv_header}\n`
for (let i =0; i < data.length; i++){
for(let key in data[i]){
scv += `${data[i][key]},`
}
scv += "\n"
}
const link = document.createElement('a');
link.href = `data:text/csv;charset=utf-8,\ufeff${encodeURIComponent(scv)}`;
link.download = `${fileName}.csv`;
document.body.appendChild(link)
link.click();
document.body.removeChild(link)
console.log("成功下载")
}
const dataSource= [
{
"id": 1,
"event": "早餐",
"money": 5,
"remark": "吃"
},
{
"id": 2,
"event": "中餐",
"money": 12,
"remark": "吃"
},
{
"id": 3,
"event": "晚餐",
"money": 12,
"remark": "交通"
}
]
const btn = document.getElementById("btn")
btn.onclick = () => {
downScv("test", dataSource)
}
</script>
</html>
- 结果
思考和问题
-
wps打开之后会有警告。 -
修改参数一样的下载,并且可以修改文件名后缀。
|