一、下载插件(xlsx如果报错utils未定义就用下面这个版本)
npm install --save xlsx@0.17.0
npm install --save file-saver@2.0.5
二、页面中引入
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
三、导入/导出表格内容
1.导出
exportExcel() {
//假设你有一个名为data的数组,其中包含要导出的数据
const data = [
{ id: 1, name: '小明', age: 18, salary: 8000 },
{ id: 2, name: '老王', age: 40, salary: 2000 },
{ id: 3, name: '李红', age: 30, salary: 4000 },
];
// 设置表头
const header = ['ID', '姓名', '年龄', '工资']; // 列标题数组
// 将表头与数据合并,遍历data,将数组对象转为二维数组
const dataArray = [header, ...data.map(item => [item.id, item.name, item.age, item.salary])];
// 创建 workbook 对象
const workbook = XLSX.utils.book_new();
// 将数据转换为 worksheet 对象,
//'{ skipHeader: true }':去除表格第一行,不加这个属性的话表格第一行会有一行序号
const worksheet = XLSX.utils.json_to_sheet(dataArray, { skipHeader: true });
// 将 worksheet 添加到 workbook 中
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
// 将 workbook 保存为 Excel 文件
const excelData = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
const blob = new Blob([excelData], { type: 'application/octet-stream' }
);
// data就是文件名称,可自行修改
saveAs(blob, 'data.xlsx');
},
2.导入
ImportData() {
let _this = this;
var f = event.currentTarget.files[0];
var reader = new FileReader();
FileReader.prototype.readAsBinaryString = function (f) {
var binary = "";
var wb; //读取完成的数据
var outdata;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
var XLSX = require("xlsx");
wb = XLSX.read(binary, {
type: "binary"
});
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
console.log('上传的数据:', outdata);
//此处可对数据进行处理
let arr = [];
outdata.map(v => {
let obj = {}
obj.id = v['ID']
obj.name = v['姓名']
obj.age = v['年龄']
obj.salary = v['工资']
arr.push(obj)
});
if (arr.length > 0) {
_this.$message({
type: "success",
message: "上传成功"
})
}
_this.list = _this.list.concat(arr)//合并原有数组
return arr;
};
reader.readAsArrayBuffer(f);
};
reader.readAsBinaryString(f);
},
标签:XLSX,const,excel,导出,workbook,导入,reader,var,obj
From: https://blog.csdn.net/weixin_48095278/article/details/139091168