安装xlsx
npm i xlsx --save
页面代码
<template>
<div>
<button @click="open">点击渲染</button>
<div v-html="excelData" class="excelForm"></div>
</div>
</template>
使用axios下载文件地址
request({
url: 路径,
method: 'GET',
responseType: 'arraybuffer', // 使用 arraybuffer 来接收二进制数据
}).then((res) => {
loadExcelData(res.data);
console.log(res.data);
})
.catch((error) => {
console.error('下载Excel文件时出错: ', error);
})
解析文件
const loadExcelData = (data) => {
// 解析Excel文件
const arrayBuffer = new Uint8Array(data);
const workbook = XLSX.read(arrayBuffer, { type: 'array' });
const sheets = workbook.Sheets; // 获取文档数据
// 假设要渲染第一个工作表
const worksheet = sheets[workbook.SheetNames[0]];
excelData.value = XLSX.utils.sheet_to_html(worksheet);
console.log(data.excelData);
}
小结: /* 在使用了scoped的情况下样式不生效,就要用深度作用选择器 >>>、:deep() 等 */,
pc端可以直接使用// window.open(url) // window.location.href = url