纯前端利用 js-xlsx 实现 Excel 文件导入导出功能示例
时间: 2024-03-07 15:48:20 浏览: 143
好的,以下是一个利用 js-xlsx 实现 Excel 文件导入导出功能的示例:
首先在 HTML 文件中引入 js-xlsx 库:
```html
<script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>
```
然后在 JavaScript 文件中编写以下代码:
```javascript
// 导出 Excel 文件
function exportExcel(data, filename) {
const ws = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
XLSX.writeFile(wb, `${filename}.xlsx`);
}
// 导入 Excel 文件
function importExcel(file, callback) {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const result = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
callback(result);
};
}
```
其中,exportExcel 函数用于将数据导出为 Excel 文件,参数 data 为要导出的数据,filename 为导出的文件名。
importExcel 函数用于导入 Excel 文件,参数 file 为要导入的文件,callback 为导入成功后的回调函数,回调函数的参数 result 为导入的数据。
示例代码中使用了 FileReader 对象读取文件内容,然后使用 js-xlsx 库解析 Excel 文件并将数据转化为 JSON 格式。
使用示例:
```javascript
const data = [
{ name: '张三', age: 20, gender: '男' },
{ name: '李四', age: 22, gender: '女' },
{ name: '王五', age: 25, gender: '男' },
];
exportExcel(data, 'test'); // 导出 Excel 文件,文件名为 test.xlsx
const inputElement = document.getElementById('input-file');
inputElement.addEventListener('change', (e) => {
const file = e.target.files[0];
importExcel(file, (result) => {
console.log(result); // 输出导入的数据
});
});
```
在 HTML 文件中添加一个文件选择框:
```html
<input type="file" id="input-file">
```
用户选择一个 Excel 文件后,调用 importExcel 函数导入数据,并在回调函数中处理导入的数据。
阅读全文
相关推荐

















