vue3 ts在线预览word与excel
时间: 2023-08-13 21:12:22 浏览: 200
在线预览word.Excel
3星 · 编辑精心推荐
要实现Vue3 TS在线预览Word和Excel文件,需要使用第三方库。以下是一个基于Office Web Viewer的示例代码:
1. 首先安装依赖:
```
npm install --save office-ui-fabric-core@11.0.0 office-ui-fabric-react@7.0.0 office-ui-fabric-js@1.4.0
```
2. 引入相关的模块:
```
import { Fabric } from 'office-ui-fabric-react/lib/Fabric';
import { initializeIcons } from '@uifabric/icons';
import { IOUtils } from '@microsoft/office-js-helpers';
```
3. 初始化图标和Office Web Viewer:
```
initializeIcons();
const officeJS = new OfficeJS({
host: OfficeJS.HostType.WEB,
platform: OfficeJS.PlatformType.PC,
version: '16.00'
});
```
4. 在Vue组件的template中添加一个用于渲染预览的div:
```
<template>
<div>
<div ref="previewContainer"></div>
</div>
</template>
```
5. 在Vue组件的script中使用以下代码加载Word或Excel文件:
```
import { Fabric } from 'office-ui-fabric-react/lib/Fabric';
import { initializeIcons } from '@uifabric/icons';
import { IOUtils } from '@microsoft/office-js-helpers';
export default {
name: 'FilePreview',
props: {
fileUrl: String,
fileType: {
type: String,
default: 'Word'
}
},
mounted() {
this.loadPreview();
},
methods: {
async loadPreview() {
const previewContainer = this.$refs.previewContainer;
const fabric = new Fabric();
fabric.initialize();
const result = await IOUtils.xhr({
url: this.fileUrl,
responseType: 'arraybuffer'
});
const fileArray = this.arrayBufferToBase64(result.response);
const fileBase64 = `data:${this.getFileMimeType()};base64,${fileArray}`;
const viewer = new OfficeViewer({
appEl: previewContainer,
fileType: this.fileType,
fileUrl: fileBase64,
officeJS: officeJS
});
viewer.render();
},
getFileMimeType() {
switch (this.fileType) {
case 'Excel':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
case 'Word':
default:
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
}
},
arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
}
};
```
这样就实现了Vue3 TypeScript在线预览Word和Excel文件。请注意,Office Web Viewer需要联网才能工作,因为它使用了云端的Office服务。
阅读全文