前端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>'
    }
  })
}
相关推荐
用户479492835691525 分钟前
给客户做私有化部署,我是如何优雅搞定 NPM 依赖管理的?
前端·后端·程序员
C_心欲无痕31 分钟前
vue3 - markRaw标记为非响应式对象
前端·javascript·vue.js
qingyun98944 分钟前
深度优先遍历:JavaScript递归查找树形数据结构中的节点标签
前端·javascript·数据结构
熬夜敲代码的小N1 小时前
Vue (Official)重磅更新!Vue Language Tools 3.2功能一览!
前端·javascript·vue.js
90后的晨仔1 小时前
用 Python 脚本一键重命名序列帧图片的名称
前端
辰同学ovo1 小时前
Vue 2 路由指南:从入门到实战优化
前端·vue.js
小彭努力中1 小时前
1.在 Vue 3 中使用 Cesium 快速展示三维地球
前端·javascript·vue.js·#地图开发·#cesium·#vue3
一字白首1 小时前
Vue3 进阶,新特性 defineOptions/defineModel+Pinia 状态管理全解析
前端·javascript·vue.js
90后的晨仔1 小时前
🛠️ 为什么配置 ~/.ssh/config 后,Sourcetree 就能正常推送了?
前端
Sylus_sui2 小时前
Vue2 与 Vue3 数据双向绑定:区别与原理详解
前端·javascript·vue.js