小工具知识网

当前位置: 首页 > 行业知识 > vue 前端预览 Excel 表

行业知识

vue 前端预览 Excel 表

2026-11-14 09:03:43 来源:互联网转载

一、安装依赖包官网

npm i luckyexcel

template 模板

 

二、加载

异步加载及
import LuckyExcel from 'luckyexcel';/* 下列代码加载 cdn 文件,你也可以在 public 文件夹在 html 中引入 */// 封装加载 src 文件方法function asynLoad(src, isCss = false) {  return new Promise(res => {    let el;    if (isCss) {      el = document.createElement('link');      el.rel = 'stylesheet';      el.href = src;    } else {      el = document.createElement('script');      el.src = src;    }    document.documentElement.appendChild(el);    el.onload = el.onreadystatechange = function() {      if (        !this.readyState ||        this.readyState == 'loaded' ||        this.readyState == 'complete'      ) {        res(true);      }      this.onload = this.onreadystatechange = null;    };  });}/* Vue 中加载 cdn 文件 */export default{  created() {    this.loadPlugins();  },  methods: {    loadPlugins() {      const baseURL = '//cdn.jsdelivr.net/npm/luckysheet@latest/dist';      this.loading = true;      this.tip = '正在加载依赖插件,请耐心等待...';      Promise.all([        asynLoad(`${baseURL}/plugins/css/pluginsCss.css`, true),        asynLoad(`${baseURL}/plugins/plugins.css`, true),        asynLoad(`${baseURL}/css/luckysheet.css`, true),        asynLoad(`${baseURL}/assets/iconfont/iconfont.css`, true),        asynLoad(`${baseURL}/plugins/js/plugin.js`),        asynLoad(`${baseURL}/luckysheet.umd.js`)      ])        .then(() => {          luckysheet = (window as any).luckysheet;          this.getOriginFile(); // 获取远端文件        })        .catch(res => {          this.loading = false;          this.errStatus = 1;          this.errorTitle = '插件加载失败,请刷新后重试!';        })    }  },}

cdn 加载 index.html 文件

 

三、页面使用

/* Vue 中加载 cdn 文件 */export default{  methods: {   // 获取远程文件getOriginFile() {  this.tip = '正在下载文件...';  this.loading = true  axios({    url: this.fileURL,    responseType: 'blob'  }).then(({ data }) => {    const blob = new Blob([data]);    const file = new File([blob], this.fileName);    this.init(file); // 开始渲染  }).catch(e => {    this.errorTitle = '文件解析失败,请下载后使用 Excel 打开或点击重试!'    this.errStatus = 2;  }).finally(() => {    this.loading = false;  })}// 渲染方法,接受文件对象,如果是本地文件直接传入文件即可init(file: File) {  luckysheet.destroy(); // 先销毁当前容器  LuckyExcel.transformExcelToLucky(file, exportJson => {    if (exportJson.sheets === null || !exportJson.sheets.length) {      this.$message.error('无法读取excel文件的内容,当前不支持xls文件!');      return;    }    luckysheet.create({      container: 'luckysheet',      showinfobar: false,      lang: 'zh',      data: exportJson.sheets,      title: exportJson.info.name,      userInfo: exportJson.info.name.creator    });  });}  },}

上一篇:for each和for of的区别

下一篇:删除的艺术,轻松掌握处理多余内容的秘诀!