分享

jacob 给word 指定位置添加超级链接

 三十的狼 2019-05-21
             利用jacob给word 指定位置的文字添加超链接,思路先是通过搜索找到指定位置的文字,然后进行替换添加超链接,代码如下:
package com.jstrd.mobile.security;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class TestHyperlinks {
public static ActiveXComponent word;
public static Dispatch selection;
public static Dispatch wordFile;
public static Dispatch documents;

//查找指定文字
public static boolean find(String toFindText) {

if (toFindText == null || toFindText.equals(""))
return false;
// 从selection所在位置开始查询
Dispatch find = Dispatch.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", toFindText);
// 向前查找
Dispatch.put(find, "Forward", "True");
// 设置格式
Dispatch.put(find, "Format", "True");
// 大小写匹配
Dispatch.put(find, "MatchCase", "True");
// 全字匹配
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
boolean cc= Dispatch.call(find, "Execute").getBoolean();

return cc;
}


public static void main(String[] args){

String filePath = "E:\\test.doc";
word=new ActiveXComponent("Word.Application");

word.setProperty("Visible", false);
Dispatch documents=word.getProperty("Documents").toDispatch();
Dispatch wordFile=Dispatch.invoke(documents, "Open", Dispatch.Method, new Object[]{filePath,new Variant(true),new Variant(false)}, new int[1]).toDispatch();

selection = word.getProperty("Selection").toDispatch();
while (find("指定文字")) {
Object oRange = Dispatch.call(selection, "Range");
Dispatch Hyperlinks = Dispatch.get(wordFile, "Hyperlinks").toDispatch();
Dispatch.invoke(Hyperlinks, "Add", Dispatch.Method, new Object[] { oRange, new Variant("http://www.baidu.com"),new Variant("SubAddress"), new Variant("{}"), new Variant("指定文字")}, new int[4]).toDispatch();
Dispatch.call(selection, "MoveRight");

}
System.out.println("扫描完毕!");
Dispatch.call(wordFile, "Close", new Variant(true));
Dispatch.call(word, "Quit");
}
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多