前端直达!Vue3+SheetJS解析本地上传Excel表格,轻松预览、操作、导出!
2023-12-20 03:32:47
在 Vue.js 中巧用 SheetJS:表格数据处理利器
在现代 Web 开发中,表格数据处理是不可或缺的一部分。而作为一款强大的 JavaScript 库,SheetJS 可以轻松解析和操作 Excel 文件,为处理表格数据提供了极佳的工具。本文将详细介绍如何在 Vue.js 中使用 SheetJS,实现表格数据的导入、解析、预览和导出等功能。
安装和导入 SheetJS
在 Vue.js 项目中引入 SheetJS 非常简单:
- 安装 SheetJS:
npm install sheetjs --save
- 导入 SheetJS:
import * as XLSX from 'sheetjs-style';
解析本地上传的 Excel 文件
为了解析本地上传的 Excel 文件,需要创建一个文件上传组件:
<input type="file" @change="handleFile" accept=".xls,.xlsx" />
然后定义一个 handleFile
方法来处理用户选择的文件:
handleFile(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const data = e.target.result;
const workbook = XLSX.read(data, {type: 'binary'});
this.workbook = workbook;
};
reader.readAsBinaryString(file);
}
预览 Excel 表格数据
解析完 Excel 文件后,可以使用 v-for
指令遍历数据并将其渲染到界面:
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="row in workbook.Sheets[sheetName]" :key="row.A1">
<td>{{ row.B1 }}</td>
<td>{{ row.C1 }}</td>
<td>{{ row.D1 }}</td>
</tr>
</tbody>
</table>
绘制表格
除了预览数据,还可以使用 SheetJS 绘制表格:
const wb = XLSX.utils.book_new();
wb.SheetNames.push('Sheet1');
const ws = XLSX.utils.json_to_sheet(this.tableData);
wb.Sheets['Sheet1'] = ws;
const wbout = XLSX.write(wb, {bookType:'xlsx', type:'binary'});
然后创建一个 table-component
组件来绘制表格:
<template>
<table>
<thead>
<tr>
<th v-for="column in data.columns" :key="column">{{ column }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in data.rows" :key="row.A1">
<td v-for="column in data.columns" :key="column">{{ row[column] }}</td>
</tr>
</tbody>
</table>
</template>
导出下载表格
最后,可以使用 SheetJS 将表格数据导出为 Excel 文件并下载:
const s2ab = (s) => {
const buf = new ArrayBuffer(s.length);
const view = new Uint8Array(buf);
for (let i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
const blob = new Blob([s2ab(wbout)], {type:'application/octet-stream'});
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'data.xlsx';
link.click();
常见问题解答
-
如何限制上传的文件大小?
可以在文件上传组件的accept
属性中设置max-size
参数,例如:<input type="file" accept=".xls,.xlsx" max-size="1000000" />
。 -
如何自定义表格的样式?
SheetJS 提供了styles
选项来设置表格样式,可以在XLSX.read()
方法中指定。 -
如何冻结表格中的行或列?
可以通过freezeRows
或freezeColumns
选项冻结表格中的行或列。 -
如何处理包含公式的单元格?
SheetJS 可以解析 Excel 公式,并在读取工作簿时将其转换为 JavaScript 函数。 -
如何处理多工作表的 Excel 文件?
SheetJS 可以读取和写入多工作表的 Excel 文件,可以通过workbook.Sheets
对象访问每个工作表。