前端实现在线预览、编辑Office文档(vue版)

使用插件:Spire.Cloud在线Office文档编辑器(官网:冰蓝科技在线编辑)
无需安装,在 index.html 里面引入即可

重点:支持在线创建、编辑、保存和打印 Office (Word / Excel / PPT) 文档
助您轻松实现高效率、无纸化办公

使用浏览器打开:https://cloud.e-iceblue.***/,点击右上角头像注册/登录账号。
其次,点击菜单栏“我的应用”创建应用,获取APP ID和APP Key。

(个人理解:动态切换链接不刷新页面时显示不出来的,刷新页面才可以,错误是因为id为iframeEditor得div被替换成了ifarme,切换地址后找不到这个div,无法所以动态切换链接会报错)

<div class="reportbox">
      <a-form :layout="formLayout">
        <a-form-item>
          <a-select style="width: 180px" v-model="from.reportType">
            <a-select-option value="PeriodicAnalysis"> xxxxxxxxx报告 </a-select-option>
            <a-select-option value="FoulingAssessment"> xxxxxxxxxxxx报告 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
          <a-button type="primary" @click="queryReport" style="width: 100px"> 查询 </a-button>
        </a-form-item>
      </a-form>
      <div id="div" style="height: auto" >
      //div动态创建
   </div>
      <div v-if="show" class="pdff">
        <a-empty />
      </div>
    </div>

前端JavaScript代码实现

  generateWord() {
      var docEditor
      const urlString = this.fileUrl
      const appid = ' 你的appid '
      const appkey = ' 你的appkey '

      const innerAlert = function (message) {
        if (console && console.log) console.log(message)
      }
      const onReady = function () {
        innerAlert('Document editor ready')
      }

      const onDocumentStateChange = function (event) {
        const title = document.title.replace(/\*$/g, '')
        document.title = title + (event.data ? '*' : '')
      }

      const onError = function (event) {
        if (event) innerAlert(event.data)
      }

      function ajax(options) {
        options = options || {}
        const method = (options.type || 'GET').toUpperCase()
        let url = options.url
        let queryString = null
        if (!url) return
        if (options.data) {
          queryString = []
          for (var attr in options.data) {
            queryString.push(attr + '=' + options.data[attr])
          }
          queryString = queryString.join('&')
        }
        if (method === 'GET' && queryString) {
          url += '?' + queryString
          queryString = ''
        }
        const xhr = new XMLHttpRequest()
        xhr.open(method, url, true)
        if (method === 'POST') xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(queryString)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              var data = xhr.responseText
              if (options.dataType === 'json') data = JSON.parse(data)
              options.su***ess && options.su***ess(data)
            } else {
              options.error && options.error(xhr.status)
            }
          }
        }
      }

      // 用于保存
      const callbackfn = function (result) {
        if (result && result.data) {
          const data = result.data
          let fileName = data[0]
          const url = data[1]
          if (fileName.indexOf('=') > -1) fileName = fileName.split('=')[1]
          ajax({
            url: '',
            type: 'post',
            data: { filename: fileName, fileuri: url },
            dataType: 'json',
            async: false,
            su***ess: function (json) {
              if (json.code == 200 || json.code == '200') {
                alert('保存成功')
              } else {
                this.error(json, '保存失败')
              }
            },
            error: function (json, msg) {
              alert(+msg)
            },
          })
        }
      }
      docEditor = new SpireCloudEditor.OpenApi(
        'iframeEditor',
        {
          fileAttrs: {
            fileInfo: {
              name: this.fileName,  // this.fileName动态返回
              ext: 'docx',
              primary: String(new Date().getTime()),
              creator: '',
              createTime: new Date(),
            },
            sourceUrl: urlString,   // urlString动态返回
            createUrl: '',
            callbackUrl: '', This item can be empty, but only if the 'onSave' callback function must be defined in events. If the callback function is undefined and this item is empty, Cloud Editor will not provide save function.
            verification: null, //用户文件系统下载文件时若需要验证类似token的数据可以写在这里
            canEdit: true,
            canDownload: true,
            canForcesave: true,
          },
          user: {
            primary: '',
            name: '',
            canSave: true,
            customization: {
              public: {
                ***mon: {
                  whiteLabel: false,
                  defaultZoom: 1,
                  openReviewChanges: false,
                  permGroups: ['everyone'], //限制编辑分组
                  viewVersion: false,
                  header: {
                    hideTitle: false,
                    defaultView: 'full',
                  },
                },
                word: null, //doc定制
                powerpoint: null, //ppt定制
                excel: null, //xls定制
              },
            },
          },
          editorAttrs: {
            //编辑器配置
            editorWidth: '100%',
            editorHeight: '900px',
            editorType: 'document', //编辑器类型,可不配置,程序根据文件类型获取,结果为 document,presentation,spreadsheet
            platform: 'desktop', //编辑器平台类型,可选desktop, mobile, embedded
            viewLanguage: 'zh', //平台界面展示语言可选en/zh
            canChat: true, //是否可聊天
            can***ment: true, //是否可批注
            canReview: true,
            embedded: {
              saveUrl: '',
              embedUrl: '',
              shareUrl: '',
            },
            events: {
              onReady: onReady,
              onDocumentStateChange: onDocumentStateChange,
              onError: onError,
              onSave: callbackfn,
            },
          },
        },
        appid,
        appkey,
      )
    },
    queryReport(){
    this.updatdiv() //  动态生成div 每次条件改变的时候清除div,搜索的时候创建新的div
    // axios请求 根据实际情况!apiUrl请求地址(我的项目请求地址是第三方)
     axios.get(apiUrl, {
          headers: {
            Authorization: 'Bearer ' + sessionStorage.token,
          },
          params: pam,
        })
        .then((res) => {
          // console.log(res)
          this.fileUrl = res.data.data.downloadUrl
          this.fileName = res.data.data.fileName
          this.generateWord()  // 此处调用生成word
     
        })
        .catch((error) => {
          this.show = true
          console.log(error)
          this.spinning = false
        })
    }
 //  动态生成div
 updatdiv() {
      let div = document.querySelector('#div')
      var divChild = document.createElement('div') //一级
      var childDiv = document.createElement('div') // 二级
      childDiv.id = 'iframeEditor'
      divChild.appendChild(childDiv)
      div.innerHTML = ''
      div.appendChild(divChild)
    },

这样就解决了链接更改之后word显示还是旧的链接得问题!

转载请说明出处内容投诉
CSS教程_站长资源网 » 前端实现在线预览、编辑Office文档(vue版)

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买