这篇文章介绍如何在web前端引入JS插件实现在线预览、编辑Office文档。

使用插件:Spire.Cloud在线Office文档编辑器(官网:冰蓝科技在线编辑

重点:该方案仅需浏览器支持HTML5,提供中英文双语界面,不需要安装Office或控件,也不需要做环境配置就可以直接调用插件,非常简单。

准备工作

首先,使用浏览器打开:https://cloud.e-iceblue.cn/,点击右上角头像注册/登录账号。

其次,点击菜单栏“我的应用”创建应用,获取APP ID和APP Key。

前端JavaScript代码实现

添加以下JavaScript代码到前端页面,来集成Spire.Cloud在线编辑器实现Office文档在线预览或编辑。参数对照表已放在文章末尾。

<!DOCTYPE html>
<html>
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta HTTP-EQUIV="pragma" CONTENT="no-cache"/>
    <meta HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"/>
    <meta HTTP-EQUIV="expires" CONTENT="0">
    <title>Spire.Cloud</title>
	<style>
	
html {
    height: 100%;
    width: 100%;
}

body {
    background: #fff;
    color: #333;
    font-family: Arial, Tahoma,sans-serif;
    font-size: 12px;
    font-weight: normal;
    height: 100%;
    margin: 0;
    overflow-y: hidden;
    padding: 0;
    text-decoration: none;
}
iframe {
    border: none !important;
}

.form {
    height: 100%;
}

div {
    margin: 0;
    padding: 0;
}

	</style>
</head>
<body>
<div class="form">
    <div id="iframeEditor">
    </div>
</div>
    <script type="text/javascript" src="https://api.e-iceblue.cn/web/editors/spireapi/SpireCloudEditor.js"></script>
    <script type="text/javascript" language="javascript">
        var docEditor;
        var appid = 'your app id';
        var appkey = 'your app key';
        var config = {
    "fileAttrs": {
    "fileInfo": {
      "name": "sample.docx",
      "ext": "docx",
      "primary": String(new Date().getTime()),//this is key
      "creator": "Jonn",
      "createTime": "2022-04-18 11:30:43"
    },
    "sourceUrl": "https://cloud.e-iceblue.cn/demo/sample.docx",
    "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": "",
    "templates": {}
  },
  "user": {
    "id": "uid-1",
    "name": "Jonn",
    "canSave": true,
    "customization" : {
      "public": { 
        "common": {
          "whiteLabel": false,
          "defaultZoom": 1,
          "openReviewChanges": false,
          "viewVersion": false,
          "tokenValue": "",
          "permGroups": ["everyone"],
          "socket_url": "", 
          "header": {
            "hideTitle": false,
            "defaultView": "full"
          },
          "goback": { "url" : "" }
        },
        "document": null, 
        "excel":null,
        "powerpoint":null
      },
       "private": { 
        "token": "", 
        "appid": "",
        "appkey": ""
      }
    }
  },
  "editorAttrs": {
    "editorMode": "edit",
    "editorWidth": "100%",
    "editorHeight": "100%",
    "editorType": "document", 
    "platform": "desktop", //desktop, mobile, embedded
    "viewLanguage": "zh", //en/zh
    "events": {}
  }
};
        var innerAlert = function (message) {
            if (console && console.log)
                console.log(message);
        };

        var onAppReady = function () {
        };

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

        var onRequestEditRights = function () {
            location.href = location.href.replace(RegExp("mode=view\&?", "i"), "");
        };

        var onRequestHistory = function (event) {
            var historyObj = null;

            docEditor.refreshHistory(
                {
                    currentVersion: "1",
                    history: historyObj
                });
        };

        var onRequestHistoryData = function (data) {
            var version = data.data;
            var historyData = null;

            docEditor.setHistoryData(historyData[version-1]);
        };

        var onRequestHistoryClose = function (event){
            document.location.reload();
        };

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

        var onOutdatedVersion = function (event) {
            location.reload(true);
        };
        var onDownload = function(props){
            alert('fileName:'+props.data[0]+'fileUrl:'+props.data[1]);
            console.log('fileName:'+props.data[0]);
            console.log('fileUrl:'+props.data[1]);
        };

        var reloadFrame = function(){
            docEditor.reload();
        };

	 var callbackfn = function (result) {
            if (result && result.data) {
                var data = result.data,
                    fileName = data[0],
                    url = data[1];
                if (fileName.indexOf('=') > -1)
                    fileName = fileName.split('=')[1];
                var host1 = location.hostname;
                var host ='';
                ajax({
                    url: '',
                    type: 'post',
                    data: { 'filename': fileName, 'fileuri': url },
                    dataType: 'json',
                    async: false,
                    success: function (json) {
                        if (json.code == 200 || json.code == '200') {
                            alert('保存成功');
                        } else {
                            this.error(json, '保存失败');
                        }
                    },
                    error: function (json, msg) {
                        alert(+msg);
                    }
                });
            }
        };

        var connectEditor = function () {
            config.editorAttrs.events = {
                "onReady": onAppReady,
                "onDocumentStateChange": onDocumentStateChange,
                'onRequestEditRights': onRequestEditRights,
                "onError": onError,
                "onRequestHistory":  onRequestHistory,
                "onRequestHistoryData": onRequestHistoryData,
                "onRequestHistoryClose": onRequestHistoryClose,
                "onOutdatedVersion": onOutdatedVersion,
                'onSave': callbackfn
            };
            docEditor = new SpireCloudEditor.OpenApi('iframeEditor', config,appid,appkey);
            fixSize();
        };

        var onSaveClick = function () {
            docEditor.onSaveClick();
        }
        var fixSize = function () {
            var wrapEl = document.getElementsByClassName("form");
            if (wrapEl.length) {
                wrapEl[0].style.height = screen.availHeight + "px";
                window.scrollTo(0, -1);
                wrapEl[0].style.height = window.innerHeight + "px";
            }
        };

        if (window.addEventListener) {
            window.addEventListener("load", connectEditor);
            window.addEventListener("resize", fixSize);
        } else if (window.attachEvent) {
            window.attachEvent("onload", connectEditor);
            window.attachEvent("onresize", fixSize);
        }
		
    </script>
</body>
</html>

以上代码中的appidappkey参数要更改为你自己的App IDApp Key"sourceUrl": "https://cloud.e-iceblue.cn/demo/sample.docx" 参数要改为你自己的文档地址,同时要确保路径存在并且有访问权限。

我这里只是介绍了简单的预览、编辑的前端实现代码,如果需要把文档保存到服务器,需要设置callBackUrl参数(回调URL),这块要配合后端代码去实现。

编辑Word文档效果图如下:

参数对照表:

配置参数

示例值解释

设置值

fileAttrs
fileInfo

文档信息

name

文档名称

可为空

ext

文档后缀

docx, xlsx, pptx

primary

This is the key

可为空

creator

作者

可为空

createTime

创建时间

可为空

sourceUrl

URL

不能为空,且需有访问权限

createUrl

URL

可为空

callbackUrl

回调 URL

可为空,若需使用在线编辑的保存功能,则必须定义回调URL

verification

验证信息

可为空。用户文件系统下载文件时若需要验证类似token的数据可以写在这里

templates

文档模板

可为空

user

用户

不能为空

Id/name

冰蓝云上的 ID 和名字

可为空

Appid/appkey

Token 和 AppID/APPkey
二者必有一项不能为空

冰蓝云网站注册账号获取该信息

canSave

保存属性

默认值为true,当设置为false时,不允许保存.

customization

自定义选项

docx

public
common
whiteLabel

白标

默认值为false,当设置为true时,
不显示E-iceblue Logo 图标

defaultZoom

缩放

1

OpenReviewChagnes

是否显示跟踪变化

默认值为false,当设置为true时,显示更改痕迹

viewVersion

查看属性

默认值为false,当设置为true时,不允许保存.

permGroups

限制编辑分组

全员

socket_url

URL

可为空

header
hideTitle

隐藏标题

默认值为false,当设置为true时,标题隐藏.

defaultView

默认视图

全屏

goback

URL

可为空

editorAttrs
editorMode

编辑模式
'edit'(编辑)
'view'(展示)

不能为空,必须赋值为“edit” 或 “view”

editorWidth

可为空,默认值100%.

editorHeight

可为空,默认值100%.

editorType

文件编辑器类型

可不配置,程序根据文件类型获取,必须设置为 document 或 spreadsheet 或 presentation

platform

编辑器平台类型
'desktop'(电脑端展示)
'mobile'(手机端展示)
'embedded'(嵌入展示)

不能为空,必须设置为 desktop 或 mobile 或 embedded 中的一种

viewLanguage

平台界面展示语言

可为空。“en” 或 “zh”. 若设置为空,则匹配浏览器默认语言

canChat

是否可聊天

默认值为true,当设置为false时,不可聊天.

canComment

是否可批注

默认值为true,当设置为false时,不可批注

events

事件

"onReady", //编辑器已加载完成
"onDocumentStateChange", //当前文档状态(已保存或未保存)
"onError", //报错(返回报错信息)
"onSave" //保存(返回保存事件)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐