前端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>'
    }
  })
}
相关推荐
charlie1145141911 天前
从零开始理解 CSS:让网页“活”起来的语言2
前端·css·笔记·学习·选择器·样式表·原生
浪裡遊1 天前
Next.js路由系统
开发语言·前端·javascript·react.js·node.js·js
mapbar_front1 天前
职场中的顶级能力—服务意识
前端
尽兴-1 天前
[特殊字符] 微前端部署实战:Nginx 配置 HTTPS 与 CORS 跨域解决方案(示例版)
前端·nginx·https·跨域·cors·chrom
JIngJaneIL1 天前
助农惠农服务平台|助农服务系统|基于SprinBoot+vue的助农服务系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·助农惠农服务平台
云外天ノ☼1 天前
待办事项全栈实现:Vue3 + Node.js (Koa) + MySQL深度整合,构建生产级任务管理系统的技术实践
前端·数据库·vue.js·mysql·vue3·koa·jwt认证
一位搞嵌入式的 genius1 天前
前端实战开发(三):Vue+Pinia中三大核心问题解决方案!!!
前端·javascript·vue.js·前端实战
塞纳河畔的歌1 天前
保姆级教程 | 麒麟系统安装Edge浏览器
前端·edge
多睡觉觉1 天前
数据字典:从"猜谜游戏"到"优雅编程"的奇幻之旅
前端
嗝屁小孩纸1 天前
开发集成热门小游戏(vue+js)
前端·javascript·vue.js