安装模块 官方文档
NodeJS | SheetJS Community Edition
代码:
1 <script setup>
2 3 import { ref, onMounted } from "vue";
4 import { readFile, read, utils, writeFileXLSX } from "xlsx";
5 import * as XLSX from "xlsx";
6 const tableData = ref([]);
7 const rows = ref([]);
8 const title = ref("");
9 async function beforeUpload(file) {
10 const result = await readXLSX(file);
11 console.log(result);
12 tableData.value = result;
13 return false;
14 }
15 function readXLSX(file) {
16 return new Promise((resolve, reject) => {
17 const reader = new FileReader();
18 reader.readAsBinaryString(file);
19 reader.onload = (evt) => {
20 const data = evt.target.result;
21 const wb = XLSX.read(data, { type: "binary" });
22 rows.value = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
23 title.value = rows.value[0];
24
25 const jsonData = XLSX.utils.sheet_to_json(ws);
26 resolve(jsonData);
27 };
28 });
29 }
30
45 function exportFile() {
46 const ws = utils.json_to_sheet(rows.value);
47 const wb = utils.book_new();
48 utils.book_append_sheet(wb, ws, "Data");
49 writeFileXLSX(wb, "SheetJSVueAoO.xlsx");
50 }
51 </script>
52
53 <template>
54 <Nav />
55 <div class="warp">
56 <el-upload
57 ref="upload"
58 :auto-upload="true"
59 accept=".xls,.xlsx"
60 :before-upload="beforeUpload"
61 :show-file-list="false"
62 >
63 <template #trigger>
64 <el-button type="primary">选择文件</el-button>
65 </template>
66 </el-upload>
67 <table>
68 <thead>
69 <!-- <th class="title" v-for="(item, key) in title" :key="key">{{ key }}</th>
70 -->
71 <th>姓名</th>
72 <th>部门</th>
73 <th>个人本月业绩</th>
74 <th>全年总业绩</th>
75 <th>目标业绩</th>
76 <th>已完成业绩</th>
77 <th>进度百分比</th>
78 </thead>
79 <tbody>
80 <tr v-for="(row, idx) in rows" :key="idx">
81 <!-- <td v-for="(item, key) in title" :key="key">{{ row[key] }}</td> -->
82 <td>{{ row.制单员 }}</td>
83 <td>销售部</td>
84 </tr>
85 </tbody>
86 </table>
87 <button @click="exportFile">Export XLSX</button>
88 </div>
89 </template>
90 <style scoped>
91 .warp {
92 position: absolute;
93 top: 170px;
94 left: 220px;
95 width: 1600px;
96 }
97 table {
98 border: 1px solid #ccc;
99 border-collapse: collapse;
100 width: 100%;
101 }
102
103 table td {
104 border: 1px solid #ccc;
105 text-align: center;
106 height: 30px;
107 }
108
109 .title {
110 background: #ccc;
111 }
112 </style>