代码实现
1. 将表格数据转换为字符串格式
2. 字符串格式里面的,逗号表示换列
3. 字符串格式里面的\n符号表示换行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button type="button" id="button"> 下载文件</button>
</body>
<script type="text/javascript">
const titleTable = ['A', 'B', 'C', 'D'];
const dataTable = [{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
}, {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
}]
function onDownload() {
const data = `${
dataTable
.map((item) => [item.a, item.b, item.c, item.d].toString())
.join('\n')}\n`;
const title = `${
titleTable.toString()}\n`;
const url = `data:text/csv;charset=utf-8,\ufeff${
encodeURIComponent(`${
title}${
data}`)}`;
const link = document.createElement('a');
link.href = url;
link.download = 'test.csv';
link.click();
}
const button = document.getElementById('button')
button.onclick =onDownload()
</script>
</html>