前端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>'
    }
  })
}
相关推荐
alicema1111几秒前
萤石摄像头C++SDK应用实例
开发语言·前端·c++·qt·opencv
阿维的博客日记2 分钟前
div和span区别
前端·javascript·html
长安城没有风6 分钟前
更适合后端宝宝的前端三件套之HTML
前端·html
伍哥的传说6 分钟前
Vue3 Anime.js超级炫酷的网页动画库详解
开发语言·前端·javascript·vue.js·vue·ecmascript·vue3
欢乐小v28 分钟前
elementui-admin构建
前端·javascript·elementui
霸道流氓气质1 小时前
Vue中使用vue-3d-model实现加载3D模型预览展示
前端·javascript·vue.js
溜达溜达就好1 小时前
ubuntu22 npm install electron --save-dev 失败
前端·electron·npm
慧一居士1 小时前
Axios 完整功能介绍和完整示例演示
前端
晨岳2 小时前
web开发-CSS/JS
前端·javascript·css