在前端專案下載 CSV 檔

做法

建立 index.html 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button type="button">Download</button>
<script>
document.querySelector('button').addEventListener('click', async () => {
const content = [
['name', 'age', 'phone'],
['Alice', 24, '123-456-7890'],
['Bob', 28, '234-567-8901'],
['Charlie', 32, '345-678-9012'],
['David', 36, '456-789-0123'],
['Eve', 40, '567-890-1234'],
]
.map((row) => row.join(','))
.join('\n');

download('example.csv', new Blob([content], { type: 'text/plain' }));
});

const download = (filename, blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
</script>
</body>
</html>