当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 浏览器应用集成嵌入WPS指南

浏览器应用集成嵌入WPS指南

2020年01月17日  | 移动技术网IT编程  | 我要评论

      因为该wps插件使用npapi机制来和浏览器交互,故要求使用插件的浏览器必须支持npapi机制且必须开启npapi机制。

以下是支持的常见的浏览器及其版本:

  • firefox浏览器52及小于52的版本(高于52的版本不再支持npapi)

  • chrome浏览器45及小于45的版本(高于45的版本不再支持npapi)

  • 360浏览器 (支持npapi的版本)

  • uos浏览器 (支持npapi的版本)

      项目因使用wps金山文档在线编辑或者腾讯文档时候,对于专业的需要使用excel用户来说,在线的office文档打开的解决方案是不满足需求的,所以转向了定制版本的wps集成嵌入bs应用,当然资金足够可以考虑石墨文档、葡萄城等优秀专业的企业合作。

      应用最终表现还是优秀的,相当于直接将wps直接嵌入网页,满足各类需要。唯一缺憾的是,这个解决方案不是免费的,因为合作我们获得用于开发的wps安装包(版本号为11.8.2.8744)。浏览器推荐使用360极速版(极速模式),下面附着1张效果图

                    


提供下截止2020年1月官方开发团队提供的api文档 (nphelper)

链接: https://pan.baidu.com/s/1nnpxnodsdnah5v3sgnayaq 提取码: 25gt

【如有侵权,请私信联系作者删除】

下面开始进行编码共享步骤:

1、首先创建demo.html

<!doctype xhtml>
<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <!-- 悬浮按钮 meta -->
    <meta name="author" content="rin">
    <!-- 悬浮按钮css -->
    <link rel="stylesheet" href="../css/asidenav.css">
    <!-- jquery 在线cdn -->
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <!-- oa np 插件js -->
    <script src="../js/wps_general.js"></script>
    <script src="../js/common.js"></script>
    <!-- loading 插件js -->
    <script src="../js/spin.min.js"></script>
    <title>np插件demo</title>
    <!-- loading加载动画效果 start-->
    <script type="text/javascript">
        $(function() {
            var opts = {
                lines: 9, // the number of lines to draw
                length: 0, // the length of each line
                width: 10, // the line thickness
                radius: 15, // the radius of the inner circle
                corners: 1, // corner roundness (0..1)
                rotate: 0, // the rotation offset
                color: '#000', // #rgb or #rrggbb
                speed: 1, // rounds per second
                trail: 60, // afterglow percentage
                shadow: false, // whether to render a shadow
                hwaccel: false, // whether to use hardware acceleration
                classname: 'spinner', // the css class to assign to the spinner
                zindex: 2e9, // the z-index (defaults to 2000000000)
                top: 'auto', // top position relative to parent in px
                left: 'auto' // left position relative to parent in px
            };
            var target = document.getelementbyid('foo');
            var spinner = new spinner(opts).spin(target);
        })
    </script>
    <!-- loading end-->
    <script>
        //初始化
        var wpsframe = new wpsframe;
        /**
         * 基础参数
         */
        var app = "test";
        var userid = "a004";
        var sheetname;
        var filename = "1.xlsx"; //"测试文档.xlsx";
        var filetype = getfiletype(filename); //"xls";
        const basepath = baseurl + "/wps/template/";
        //用户文档路径
        var userfileurl = baseurl + "/" + app + "/" + userid + "/" + encodeuri(filename);
        //模板文档路径
        var templateurl = basepath + encodeuri(filename);
        //wps安装包地址
        var downloadurl = "http://abc.com/upload/soft/setup_cn_2052_11.8.2.8744_professional_vba_huayu.exe";
        //必须无中文
        const remotegeturl = basepath + encodeuri(filename);
        remotesaveurl = baseurl + "/wpscloudservice/upload?app=" + app + "&userid=" + userid;
        /**
         * 获取文件类型
         */
        function getfiletype(filename) {
            if (filename.indexof("xls") != -1) {
                filetype = "xls";
            } else if (filename.indexof("ppt") != -1) {
                filetype = "ppt";
            } else if (filename.indexof("doc") != -1) {
                filetype = "doc";
            }
            return filetype;
        }
        /**
         * 程序执行
         */
        $(document).ready(function() {
            //检测浏览器是否为360
            if (!is360browser()) {
                alert("您当前的浏览器不支持此插件,请更换为360浏览器,推荐360极速浏览器(极速模式),效果更好,注:请下载专业版wps");
                return;
            }
            //初始化控件
            init(filetype)
                //打开文档
            open(filetype, sheetname);
        })
        function openfile(filename, type) {
            userfileurl = baseurl + "/" + app + "/" + userid + "/" + encodeuri(filename);
            templateurl = basepath + encodeuri(filename);
            filetype = type;
            initchange(type)
            if ($("#sheet").val() == "") {
                sheetname = "";
            } else {
                sheetname = $("#sheet").val();
            }
            open(type, sheetname);
        }
        function savefile() {
            save(filetype);
        }
    </script>
</head>

<body>
    <!-- 加载动画效果 -->
    <div id="foo" style="width:100px; height:200px; position:absolute;left: 50%;margin-top: 360px;" hidden="hidden">
    </div>

    <div id="wps" align="right" style="width:100%; height:75%; margin:0 auto;">
    </div>
    <div style="text-align: left;margin-top: 50px;margin-left: 100px;">
        <label>指定sheet页: </label><input type="text" id="sheet" /><br/><br/>
        <a href="http://abc.com/upload/soft/setup_cn_2052_11.8.2.8744_xxxx_vba_abc.exe"><b>下载最新版本专业wps</b></a>
        <br/> 注:使用本功能前提需下载专业定制版wps,360浏览器一定是要极速模式,兼容模式不支持
    </div>

    <!-- 悬浮按钮 start-->
    <div id="nav">
        <svg width="0" height="0">
            <defs>
                <filter id="goo">
                    <fegaussianblur in="sourcegraphic" stddeviation="10" result="blur"></fegaussianblur>
                    <fecolormatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 19 -9" result="goo"></fecolormatrix>
                    <fecomposite in="sourcegraphic" in2="goo" operator="atop"></fecomposite>
                </filter>
            </defs>
        </svg>
        <div class="aside-nav bounceinup animated" id="aside-nav">
            <label for="" class="aside-menu" title="按住拖动">菜单</label>

            <a href="javascript:void(0)" onclick="openfile('1.xlsx','xls')" title="excel" class="menu-item menu-first">excel</a>
            <a href="javascript:void(0)" onclick="openfile('1.docx','doc')" title="word" class="menu-item menu-second">word</a>
            <a href="javascript:void(0)" onclick="openfile('1.pptx','ppt')" title="ppt" class="menu-item menu-third">ppt</a>
            <a href="javascript:void(0)" onclick="savefile()" title="保存" class="menu-item menu-fourth">保存</a>
        </div>
    </div>
</body>
</html>

2、分解 $(document).ready 中的初始化 和 打开方法以及 保存方法

因解决方案,一定需要浏览器支持npapi,故目前只有360浏览器可使用,或者上述阐述的其他浏览器

①初始化插件

/**
 * 默认无高宽,均原始100%
 * 初始化插件,定义属性
 * @param {*文件类型doc,xls,ppt} doctype 
 */
function init(doctype) {
    plugin.setattribute("type", "application/x-wps-np-plugin");
    plugin.setattribute("height", "100%");
    plugin.setattribute("width", "100%");
    plugin.setattribute("id", "docframe1");
    //文档类型定义
    if (doctype == "doc") {
        plugin.setattribute("app", "wps");
    } else if (doctype == "xls") {
        plugin.setattribute("app", "et");
    } else if (doctype == "ppt") {
        plugin.setattribute("app", "wpp");
    }
    var obj = document.getelementbyid('wps');
    obj.appendchild(plugin);
    return plugin;
}

②打开远程资源

此处流程为先下载远程资源,再通过打开下载后的本地临时文档,再去上传,从而达到类似直接修改云文档的效果。

因官方目前版本也在迭代,优化测试某些接口,目前word的接口较为完善,demo的打开保存都已实现,调用的是vba提供的方法。因为我们的业务较为简单,本次只叙述打开、与保存。

其余的功能,交给有兴趣的读者去自行研究,语法与vba保持一致。

function open(filetype, param) {
    //loading动画加载
    $("#foo").show();
    //下载网络资源,返回本地路径
    var res = false;
    //下载用户文件到本地,返回临时文件url
    url = plugin.application.downloadfile(userfileurl);
    if (url.indexof('error') != -1) {
        //下载文件用户文件失败,下载模板文件
        url = plugin.application.downloadfile(templateurl);
    }
    //打开本地临时文件
    res = plugin.application.opendocument(url, false);
    if (res) {
        //加载动画效果关闭
        $("#foo").hide();
        console.log("执行打开方法成功" + new date());
    }
    if (filetype == "xls") {
        //定义对象,用于后面保存方法
        workbook = plugin.application.activeworkbook;
        if (param != "" && param != undefined) {
            //本次版本号的打开指定sheet页的调用方式
            plugin.application.get_worksheets(param).select();
        }
    } else if (filetype == "ppt") {
        workbook = plugin.application.activepresentation;
    }
}

③ 保存

function save(filetype) {
    var tempurl = url;
    var arr = tempurl.split(".");
    tempurl = arr[0] + "kls." + arr[1];
    //保存到本地
    if (filetype == "doc") {
        //另存为保存到本地
        plugin.application.saveas(tempurl);
    } else if (filetype == "xls") {
        //此版本号支持编辑状态下保存excel
        plugin.application.exitedit();
        tempurl = url;
        //保存到本地
        workbook.save();
    } else if (filetype == "ppt") {
        //打开时候定义的对象,另存为文件保存到本地
        workbook.saveas(tempurl);
    }
    //上传文件到服务器,remotesaveurl服务器保存接口,tempurl本地临时文件
    var exc = plugin.uploadfile(remotesaveurl, tempurl)
    alert(exc);
}

截止上述,基础的打开保存功能均已实现。还有更多的操作,请参阅 官方文档,浏览器应用集成嵌入wps指南。

④服务器保存文件,下面示例代码为c#版本

其他版本的可以参照合作后官方提供的demo进行抓包获取,进行分析

或者参照标准http协议(java版本) https://blog.csdn.net/sjh3322/article/details/78435097

public string upload(string app,string userid)
        {
            string path = string.empty;
            path = "~/" + app + "/" + userid + "/";
            //获取文件
            httppostedfilebase file = request.files["file"];
            if (file != null)
            {
                //是否存在这个app应用
                if (system.io.directory.exists(server.mappath(path)) == false)
                {
                    system.io.directory.createdirectory(server.mappath(path));
                }
                string filename = file.filename;
                string extension = path.getextension(filename);
                filename = filename.substring(0, filename.length - extension.length);
                path = path + filename.replace("kls",string.empty)+ extension;
                if (system.io.file.exists(path.getfullpath(path)))
                {
                    system.io.file.delete(path.getfullpath(path));
                }
                file.saveas(system.web.httpcontext.current.server.mappath(path));
            }
            return "success";
        }


至此,浏览器应用集成嵌入wps,打开服务器文档及保存功能实现,目前仅支持excel、word、ppt。

希望能够给有需要的小伙伴一个参考,也欢迎大家能够提些建议。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网