Skip to content
开发文档
能力中心
应用市场
WebOffice
开发者后台

最佳做法


1.默认参数

Java中不提供函数默认参数,因而调用接口时必须给定义的所有参数都传参,如果某个对应位置的参数需要使用默认值,请传递 Variant.getMissing(),例如:

javascript
app.get_ActiveDocument().Protect(WdProtectionType.wdAllowOnlyReading,
    Variant.getMissing(),
    Variant.getMissing(),
    Variant.getMissing(),
    Variant.getMissing()
);

2.函数返回值

返回值是api对象类型的接口可以直接判断返回值是否为null进行容错校验,如 Application.get_ActiveDocument() 无返回值或返回值是数字,字符串等类型的接口,需捕获Exception异常,以此判断操作是否执行成功。

3.属性获取和设置

所有对象的属性在设置和获取时,在java中均需使用加上get_或put_前缀的对应方法,无法通过“对象名.属性”直接调用,例如:

javascript
CommandBarControl controlOfd = commandBar.get_Controls().get_Item(26);
controlOfd.put_Visible(false);
// 不能使用 controlOfd.visible = false;

4.关于lcid参数

遇到接口参数名为 lcid 的参数,默认传递2052即可。

5.Canves句柄说明

5.1.获取用于装载WPS的Canves的句柄(pid和peer)的语句,必须在 mainFrame.setVisible(true) 之后调用,否则拿到空指针。
5.2.获取用于装载WPS的Canves的句柄(pid和peer)的语句,不能写在JPanel的构造函数里,必须在JPanel对象创建完成后再获取,否则拿到空指针。

6.注册事件回调流程

6.1.注册关闭事件。

javascript
EventCookie cookie = 
    app.advise(ApplicationEvents4.class, new ApplicationEvents4() {
        @Override
        public void DocumentBeforeClose(Document doc, Holder<Boolean> cancel) {
            JOptionPane.showMessageDialog(null,"关闭事件被拦截");
            cancel.value = true; //cancel为true,代表取消关闭
        }
    });

6.2.取消注册关闭事件。

6.3.添加一个按钮,给按钮注册事件

javascript
cookie.close();
cookie = null;
javascript
//添加一个按钮
CommandBar bar = app.get_CommandBars().Add(
    "test", 1, Variant.getMissing(), Variant.getMissing());
CommandBarControl control = 
    bar.get_Controls().Add(1, 1, "test", 1, "test");
bar.put_Visible(true);
control.put_Visible(true);
control.put_Caption("test");

//给按钮注册事件
EventCookie cookie = control.advise(_CommandBarButtonEvents.class,
    new _CommandBarButtonEvents() {
        @Override
        public void Click(CommandBarButton ctrl, Holder<Boolean> cancelDefault) {
            JOptionPane.showMessageDialog(null,"你点击了按钮 test");
            cancelDefault.value = true;
        }
    });

6.4.取消注册按钮时间

javascript
cookie.close(); cookie = null;

7.调用WPS 2016程序的说明

JavaAPI Demo中默认开启了加密,在WPS2016下会导致新建文档阻塞。使用WPS2016的用户需要将代码中这一行前面的注释去掉:

javascript
args.setCrypted(false); //wps2016需要关闭加密