vue项目预览excel表格(file-viewer插件)

file-viewer的插件github地址如下

点我

场景

我没有直接使用file-viewer,是按照网上搜来的方法,只使用了file-viewer的预览xlsx的功能,它里面还有预览ppt,pdf,图片等功能。

在这里插入图片描述

第一步:安装相关依赖包(exceljs,)

npm install exceljs --save
npm install '@handsontable/vue' --save
npm install handsontable --save
npm install 'handsontable/i18n' --save //这个依赖我没有下成功,不过也能正常运行

第二步:新建一个xlsxView的文件夹,将file-viewer里相关预览xlsx的代码放进去。

在这里插入图片描述在这里插入图片描述

第三步:新窗口打开,在预览组件里引入并写逻辑

html部分

<template>
  <div>
    <div v-if="fileType === 'xlsx'" ref="output" />
    <div v-if="fileType === 'pptx'" ref="pptRef"></div>
  </div>
</template>

js部分

import renderSheet from '../xlsxView'; // 引入
// mounted生命周期
mounted() {
    
    
	// 从路由地址中获取fileUrl,fileType
    this.fileUrl = this.$route.query.fileUrl ? this.$route.query.fileUrl : null
    this.fileType = this.$route.query.fileType ? this.$route.query.fileType : null
    if (this.fileUrl == null) {
    
    
      this.$message({
    
    
        type: 'error',
        message: '文件地址无效,请刷新后重试'
      })
    }
    // 加载文件内容
    this.uploading(this.fileUrl)
}
// methods方法
methods: {
    
    
	// 加载文件内容
    uploading(file) {
    
    
    	// downloadFileXLS是接口,fileKey传的是文件地址,调接口获取文件流
        downloadFileXLS({
    
    fileKey: file}).then(res => {
    
    
          if(this.fileType === 'xlsx') {
    
    
          	// 预览xlsx
            this.displayResult(res)
          } else if(this.fileType === 'pptx') {
    
    
          	// 预览pptx,可忽略,该篇文章不涉及pptx的预览
            this.previewPptx(res)
          }
        })
    },
    displayResult(buffer) {
    
    
 	  // 生成新的dom
      const node = document.createElement('div')
      // 添加孩子,防止vue实例替换dom元素
      if (this.last) {
    
    
        this.$refs.output.removeChild(this.last.$el)
        this.last.$destroy()
      }
      const child = this.$refs.output.appendChild(node)
      // 调用渲染方法进行渲染
      return new Promise((resolve, reject) =>
        renderSheet(buffer, child).then(resolve).catch(reject)
      )
    }
}

总结

还有一种使用luckysheet和luckyexcel来实现预览excel的方法,链接如下。
vue项目使用luckyexcel预览excel表格

猜你喜欢

转载自blog.csdn.net/zhangxiaodui/article/details/130133256