WPS WebOffice 提供了网页版的 Office 文档在线查看与编辑能力,通过官方 JS-SDK 可以在浏览器中打开 WPS 文档,并支持在线编辑、保存、打印等操作。整体流程为:下载 JS-SDK → 引用 SDK → 后端提供文档链接与 token → 前端初始化

相关链接

下载 JS-SDK

在使用之前,请先下载最新版本的 js-sdk 代码。

引用 JS-SDK

  • 非模块化
1
<script src="web-office-sdk.umd.js"></script>
  • CommonJS 规范
1
let WebOfficeSDK = require("./web-office-sdk.cjs.js");
  • 非模块化
1
import WebOfficeSDK from "./web-office-sdk.es.js";

使用

核心步骤说明:

  1. WebOfficeSDK.config({ url, mount }):初始化 SDK,url 为后端提供的文档地址,mount 指定挂载的 DOM 元素
  2. wps.setToken({ token, timeout }):设置鉴权 token,timeout 为 token 有效期(毫秒),到期后需重新设置
  3. 需在 onMounted 中调用,确保挂载容器已渲染完成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
<div class="wps"><div class="custom-mount"></div></div>
</template>
<script setup lang="ts">
import { onMounted } from "vue";
import WebOfficeSDK from './web-office-sdk.es.js';
const init = async () => {
const url = ''; // 后端提供的链接
const token = "";
const wps = WebOfficeSDK.config({
url: url,
mount: document.querySelector(".custom-mount")!,
});
wps.setToken({
token: token,
timeout: 10000,
});
};
onMounted(() => {
init();
});
</script>
<style lang="less" scoped>
.wps {
width: 100%;
height: 900px;
background-color: #66ccff;
.custom-mount {
width: 100%;
height: 100%;
}
}
</style>