ly2011 / blog

前端学习笔记
https://ly2011.github.io/blog
122 stars 12 forks source link

在浏览器中查看 Office 文档:Office Web Viewer #183

Open ly2011 opened 4 years ago

ly2011 commented 4 years ago

在浏览器中查看 Office 文档:Office Web Viewer

近来老板说我们的系统需要支持在线预览附件(word/excel/ppt等)

技术实现无非就是要么由后端要么由前端实现。

之前听说其他兄弟部门是由后端转换为PDF/HTML文件实现的,那么前端有没有实现预览的方案呢?

答案是有的,那就是: Office Web Viewer

什么是 Office Web Viewer?

这是一项可创建 Office Web Viewer 链接的服务。Office Web Viewer 链接将在浏览器中打开原本要下载的 Word、PowerPoint 或 Excel 文件。您可轻松将一个下载链接变成一个 Office Web Viewer 链接以在您的网站或博客中使用(例如食谱、照片幻灯片演示、菜单或预算模板)。

Office Web Viewer 的好处包括:

如何开始使用

若要使用 Office Web Viewer,请单击此链接:http://officewebviewer.com

然后将文档的 URL 复制并粘贴到文本框中,如下所示:

img

若要自行制作 URL,您可使用以下链接,其中 <文档位置> 是文档的 URL。

http://view.officeapps.live.com/op/view.aspx?src=<文档位置>

注意:<文档位置> 必须是编码的 URL,并且文档在 Internet 上必须是可公开访问的。

以下是 Office Web Viewer 中的文档的一些示例:

如果您的文档是一个 Office 文档,并且在 Internet 上可公开访问,那么您便可顺利开始。Office Web Viewer 链接很好地替换了下载链接,因为您的读者无需特殊程序也能查看您的文档,并且他们无需退出其浏览器。

实现方法

//文件预览
const showPreviewUrl = (url) => {
  const docUrl = 'https://view.officeapps.live.com/op/view.aspx?src=';
  let docArr = ['doc', 'docx', 'docm', 'dotm', 'dotx', 'xlsx', 'xlsb', 'xls', 'xlsm', 'pptx', 'ppsx', 'ppt', 'pps', 'pptm', 'potm', 'ppam', 'potx', 'ppsm'];
  const extension = file.extension;
  const index = docArr.findIndex(item => item == extension);
  if (index !== -1) {
      url = docUrl + url;
  }
  return url;
}

参考文档

  1. Office Web Viewer:在浏览器中查看 Office 文档