1.获取后端返回的二进制流
//安装xlsx插件
npm install xlsx -s
//在页面引入xlsx
impory XLSX from 'xlsx'
//如果是axios请求,responseType需要设置为arraybuffer
//获取并处理返回的信息
let data = new Uint8Array(res);
let workbook = XLSX.read(data, { type: "array" });
let sheetNames = workbook.SheetNames; // 工作表名称集合
var worksheet = workbook.Sheets[sheetNames];
var dataNow = XLSX.utils.sheet_to_json(worksheet);
console.log(dataNow);
2.本地上传表格文件并获取内容
//获取到本地上传的内容作为this.file
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
const workbook = XLSX.read(data, {
type: "binary", // 以字符编码的方式解析
});
const exlname = workbook.SheetNames[0]; // 取第一张表
let exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]); // 生成json表格内容
console.log(exl);
} catch (e) {
console.log("出错了::"+e);
return false;
}
};
fileReader.readAsBinaryString(this.file);