因为该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);
}

截止上述,基础的打开保存功能均已实现。还有更多的操作,请参阅 https://open.wps.cn/docs/office 官方文档,浏览器应用集成嵌入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(, 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。

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

本文为原创文章,转载请标明出处。

最新文章

  1. 天气预报API开发
  2. 那些让IE6-8羞愧的替补型js
  3. python学习笔记:Day02
  4. FlashFXP|FTP
  5. [译] ASP.NET MVC 6 attribute routing – the [controller] and [action] tokens
  6. LCA算法倍增算法(洛谷3379模板题)
  7. 权威发布:长链非编码RNA命名规则
  8. URAL 2073 Log Files (模拟)
  9. prepare a mysql docker server
  10. 搭建Spring、Spring MVC、Mybatis和Freemarker
  11. nyist 61 传纸条 nyist 712 探 寻 宝 藏(双线程dp问题)
  12. url 的httppost 和http get ,put,delect
  13. LeetCode 643. Maximum Average Subarray I (最大平均值子数组之一)
  14. vue 之webpack打包工具的使用
  15. Mysql连接数太多ERROR 1040 (HY000): Too many connections
  16. [leetcode]81. Search in Rotated Sorted Array II旋转过有序数组里找目标值II(有重)
  17. Rop框架学习笔记
  18. python 字符串的一些方法
  19. 75.Java异常处理机制throws
  20. 基于 Python 和 Pandas 的数据分析(5) --- Concatenating and Appending

热门文章

  1. springboot + redis + 注解 + 拦截器 实现接口幂等性校验
  2. Gyn 100989 &quot;1D Cafeteria (B)&quot;(set+lower_bound)
  3. 使用cnpm i -S axios 遇到报错Install fail! Error: EISDIR: illegal operation on a directory, symlink..........的解决办法
  4. jquery银行电子账单表格填入和编辑插件
  5. 深浅Copy的理解
  6. TransactionDefinition接口中定义了七个事务传播行为
  7. URL参数中加号“+”丢失的问题
  8. QT中加载动态链接库
  9. 如何删除Word自动编号后文字和编号之间的空白距离
  10. 一次面试题,将 字符串 保存在 Byte 数组中