vue+element UI Excel导入导出
在Vue项目中使用Element UI实现Excel的导入和导出,可以使用第三方库如xlsx
和file-saver
。以下是一个简单的例子:
- 安装依赖:
npm install xlsx file-saver
- 在Vue组件中使用:
<template>
<div>
<el-button @click="exportExcel">导出Excel</el-button>
<el-button @click="importExcel">导入Excel</el-button>
<input type="file" @change="handleFileChange" style="display: none" ref="excel-file" />
</div>
</template>
<script>
import XLSX from 'xlsx';
import { saveAs } from 'file-saver';
export default {
methods: {
exportExcel() {
// 假设你有一个表格数据数组
const data = [
['姓名', '年龄', '性别'],
['张三', 30, '男'],
['李四', 24, '女']
];
const ws = XLSX.utils.aoa_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), 'export.xlsx');
},
importExcel() {
this.$refs['excel-file'].click();
},
handleFileChange(e) {
const files = e.target.files;
if (files.length <= 0) {
return;
}
const f = files[0];
const reader = new FileReader();
reader.onload = e => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const json = XLSX.utils.sheet_to_json(worksheet);
console.log(json); // 这里可以处理你的JSON数据
};
reader.readAsArrayBuffer(f);
}
}
};
function 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;
}
</script>
``
评论已关闭