前端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>'
    }
  })
}
相关推荐
jump_jump2 小时前
超长定时器 long-timeout
前端·javascript·node.js
Mintopia3 小时前
架构进阶 🏗 从 CRUD 升级到“大工程师视野”
前端·javascript·全栈
Mintopia3 小时前
小样本学习在 WebAI 场景中的技术应用与局限
前端·人工智能·aigc
光影少年3 小时前
vue生态都有哪些?
前端·javascript·vue.js
一只大头猿3 小时前
基于SpringBoot和Vue的超市管理系统
前端·vue.js·spring boot
未来之窗软件服务3 小时前
万象EXCEL开发(十一)excel 结构化查询 ——东方仙盟金丹期
excel·仙盟创梦ide·东方仙盟·万象excel
用户1456775610373 小时前
告别繁琐操作!Excel合并原来可以这么轻松
前端
itslife3 小时前
vite 源码 - 创建 ws 服务
前端·javascript
懒人Ethan4 小时前
解决一个C# 在Framework 4.5反序列化的问题
java·前端·c#
用户1456775610374 小时前
Excel合并数据太麻烦?这个神器3秒搞定,打工人必备!
前端