# csv文件导入导出
<body>
<script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
<style>
table {
overflow: scroll;
white-space: nowrap;
border-collapse: collapse;
}
th,
td {
border: 1px solid #333;
padding: 1rem;
max-width: 10rem;
overflow: scroll;
}
</style>
<input type="file" id="fileInput" />
<button id="upload">上传</button>
<button id="download">下载</button>
<table id="table"></table>
<script>
console.log(XLSX);
let objArr;
upload.addEventListener('click', () => {
if (fileInput.files.length < 0) console.wran('请选择文件再上传!');
const fr = new FileReader();
fr.readAsArrayBuffer(fileInput.files[0]);
fr.onload = (e) => {
const buffer = fr.result;
const wb = XLSX.read(buffer, { type: "binary" });
let worksheet = wb.Sheets[wb.SheetNames[0]];
objArr = XLSX.utils.sheet_to_json(worksheet);
obj2th(objArr[0]);
objArr.forEach(item => obj2td(item));
}
});
const obj2th = (obj) => {
const thead = document.createElement("thead");
const tr = document.createElement("tr");
Object.keys(obj).map(item => {
const th = document.createElement("th");
th.innerText = item;
tr.append(th);
})
thead.append(tr);
table.append(thead);
};
const obj2td = (obj) => {
const tr = document.createElement("tr");
Object.values(obj).map(item => {
const td = document.createElement("td");
td.innerText = item;
tr.append(td);
})
table.append(tr);
};
download.addEventListener("click", () => {
const ws = XLSX.utils.json_to_sheet(objArr);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Data");
XLSX.writeFileXLSX(wb, "啦啦啦导出文件.xlsx");
})
</script>
</body>
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72