vue 实现在线预览excel

一、思路

由于项目中要求excel能够在线预览,且excel文件并非本地而是后端那边提供的。因此提供一下本人在项目的解决思路:
1.让后端返回二进制文件流
2.将文件流转为file对象
3.通过luckyexcel解析file对象,得到想对应的数据
4.将解析后得到的数据通过luckysheet进行展示

二、安装依赖

安装luckexcel:

npm i luckyexcel

安装lucksheet,由于lukysheet的引入方式只有两种cdn引入以及本地引入,暂不支持npm,因此此文采用本地引入:
将下载好的包中的dist文件夹下的所有文件复制到public目录下:
在这里插入图片描述
然后在index.html文件里引入依赖:
在这里插入图片描述

三、代码展示

1.必须要有一个容器,并且给定唯一的id,生成excel表格时会用到
2.luckyexcel只支持解析xlsx文件的数据,不支持xls(可以考虑将xls转换为xlsx)

<template>
  <div id="luckysheet" style="margin:0px;padding:0px;width:100vw;height:100vh;"></div>
</template>

<script setup>
import LuckyExcel from "luckyexcel";
import {
    
    ElMessage} from "element-plus";
import {
    
    downloadFileForData} from '@/modules/api/module1/templateManagement-new'
import {
    
    useRoute} from "vue-router";
import {
    
    onUnmounted} from "vue";

const route = useRoute()
// 获取excel文件对象,解析成luckysheet可以接受的对象
const handleShowDetail = async () => {
    
    
  const path = route.params.path.split('/')[0]
  try {
    
    
    const res = await downloadFileForData({
    
    
      path: path,
      filename: route.params.filename
    })
   // 二进制流(blob)转file对象
    const files = new window.File([res], route.params.filename, {
    
    type: "application/vnd.ms-excel;charset=utf-8"});
    LuckyExcel.transformExcelToLucky(files, exportJson => {
    
    
      if (!exportJson.sheets || exportJson.sheets.length === 0) {
    
    
        ElMessage.warning('读取excel文件内容失败');
        return;
      }
      initExcel(exportJson);
    })
  } catch (e) {
    
    
    console.log(e)
  }
}

// 初始化excel
const initExcel = (exportJson = {
     
     }) => {
    
    
  const name = route.params.filename.split('.')[0]
  // eslint-disable-next-line
  luckysheet.destroy()
  // eslint-disable-next-line
  luckysheet.create({
    
    
    container: 'luckysheet', // luckysheet为容器id
    lang: 'zh',   //默认语言
    title: name,
    data: exportJson.sheets //导入excel数据
  })
}

// 执行预览excel
handleShowDetail()

onUnmounted(() => {
    
    
  // eslint-disable-next-line
  luckysheet.destroy()
})
</script>

<style scoped>

</style>

请求的接口中的responseType为blob类型接收响应
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45150813/article/details/129121198