您的当前位置:首页>全部文章>文章详情

利用微软的Office Online实现Office文档在线预览功能

发表于:2022-11-26 13:41:26浏览:1644次TAG: #微软 #在线预览 #Office

微软也已经免费提供在线版本office预览了,一个url就可以访问。
这个文件地址需满足以下几个条件:
(1)在浏览器是可以访问的;
(2)需域名访问,IP无效;
(3)访问端口为80(不是8080哈,它俩不一样的哈)。

https://view.officeapps.live.com/op/view.aspx?src=文件地址

src后面的URL是网上能访问到的文件地址,比如http://abc.com/file/demo.xlsx

直接访问:https://view.officeapps.live.com/op/view.aspx?src=http://abc.com/file/demo.xlsx
直接访问:https://view.officeapps.live.com/op/embed.aspx?src=http://abc.com/file/demo.xlsx
参数:
src:文件链接(不支持本地)
view:只读模式,带功能菜单
embed:只读模式,只有内容区

注意,如果出现打不开的问题:
图片alt
解决办法:
1、如果是前端js之类,处理办法是给URL采用encodeURIComponent()方法。
2、或者在服务器端转码urlencode(‘URL’)过后输出到前端。

https://view.officeapps.live.com/op/view.aspx?src=encodeURIComponent(http://abc.com/file/demo.xlsx)

<el-dialog title="预览" :visible.sync="open1" width="1000px" height="800px" append-to-body>
      <iframe width="900px" height="600px"
        :src='url1'>
      </iframe>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadField">下载</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
function view(url){
 //需要判断一下是office文件还是pdf  pdf不用加微软的api
 let str =  url.substring(url.lastIndexOf(".")+1)
    if(str == 'pdf'){
       this.url1 = url
       this.open1=true;
       this.fileUrl = url
    }else{
      this.url1 = 'https://view.officeapps.live.com/op/embed.aspx?src='+url
      this.open1=true;
      this.fileUrl = url
    }
}