前端vue3获取excel二进制流在页面展示

excel二进制流在页面展示

安装xlsx

javascript 复制代码
npm install xlsx
import * as XLSX from 'xlsx';

在页面中定义一个div来展示html数据

javascript 复制代码
 <div class="file-input" id="file-input" v-html="excelData"></div>

定义二进制流请求接口

javascript 复制代码
export function getExcel(data: any) {
    return axios({
        url: 'xxx',
        method: 'post',
        responseType: 'blob',
        data,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
    });
}

拿到数据并展示

javascript 复制代码
const excelData = ref(null)

const dealFile = () => {
  let params = {}
  getExcel(params).then(async (res: any) => {
    loading.value = false
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const arrayBuffer = await blob.arrayBuffer()
    const workbook = await XLSX.read(arrayBuffer, {type: 'array'})
    const sheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[sheetName]
    console.log('worksheet   ', worksheet)
    try {
      if (worksheet) {
        const html = XLSX.utils.sheet_to_html(worksheet, {
          header: `
        <style>
          .xlsx-table {
            border-collapse: collapse;
            width: 100%;
            margin: 1rem 0;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
          }
          .xlsx-table th, .xlsx-table td {
            border: 1px solid #e0e0e0;
            padding: 10px 12px;
            text-align: left;
            min-width: 150px;
          }
          .xlsx-table th {
            background-color: #f5f7fa;
            font-weight: 600;
            color: #333;
            min-width: 150px;
          }
          .xlsx-table tr:nth-child(even) {
            background-color: #f9f9f9;
          }
          .xlsx-table tr:hover {
            background-color: #f1f5f9;
          }
        </style>
      `
        })
        excelData.value = html.replace('<table', '<table class="xlsx-table"');
      } else {
        excelData.value = '<div style="text-align: center;height:200px;line-height: 200px">暂无数据</div>'
      }
    } catch (error) {
      excelData.value = '<div style="text-align: center;height:200px;line-height: 200px">暂无数据</div>'
    }
  })
}
相关推荐
gnip18 分钟前
监听设备网络状态
前端·javascript
As33100102 小时前
Chrome 插件开发实战:打造高效浏览器扩展
前端·chrome
xrkhy2 小时前
nvm安装详细教程(卸载旧的nodejs,安装nvm、node、npm、cnpm、yarn及环境变量配置)
前端·npm·node.js
德育处主任3 小时前
p5.js 3D盒子的基础用法
前端·数据可视化·canvas
前端的阶梯3 小时前
为何我的figma-developer-mcp不可用?
前端
weixin_456904273 小时前
Vue3入口文件main.js解析
前端·javascript·vue.js
Awbeci3 小时前
微前端-解决MicroApp微前端内存泄露问题
前端
前端领航者3 小时前
重学Vue3《Vue Watch 监听器深度指南:场景、技巧与底层优化原理剖析》
前端·vue.js
布列瑟农的星空3 小时前
34岁老前端的一周学习总结(2025/8/15)
前端·后端
豆苗学前端4 小时前
vue3+TypeScript 实现一个图片占位符生成器
前端·面试·github