java操作word文档(jacob

Posted on

java操作word文档(jacob,poi)

项目需要,用户从系统里面下载word文档,该文档进行了填写限制和加密,用户只能在固定位置填写内容。现要求系统验证上传的附件是否从系统上下载下来的。

思路:系统上面的文档都加入一个固定书签,用户上传文档的时候,检验文档里是否包含这个书签。

采用jacob操作word文档

JACOB(java -com bridge)是一个 JAVA到微软的COM接口的桥梁。使用JACOB允许任何JVM访问COM对象,从而使JAVA应用程序能够调用COM对象。

下载地址:http://sourceforge.net/projects/jacob-project/

其中jacob-1.16.1-x64.dll 是用于64位机器上的,jacob-1.16.1-x86.dll用于32位的。

该dll放于 C:\Windows\system32 目录下。jacob.jar放于应用lib底下

测试代码 Java代码 收藏代码

  1. ActiveXComponent word = null;
  2. try {
  3. word = new ActiveXComponent("Word.Application");
  4. System.out.println("jacob当前版本:"+word.getBuildVersion());
  5. }catch(Exception e ){
  6. e.printStackTrace();
  7. }

ActiveXComponent word = null;

try { word = new ActiveXComponent("Word.Application");

    System.out.println("jacob当前版本:"+word.getBuildVersion());

}catch(Exception e ){

     e.printStackTrace();

}

下面再贴出网上常见的代码+自己整理的几个方法(模糊查询书签等)

注意插入书签+书签值的方法,要先插入书签值再选中书签值,之后插入书签。这样根据书签名才能取得书签值。否则根据网络上很多方法,都取不到书签值或者取到空。因为书签值可以是一个点也可以是一大段内容。 Java代码 收藏代码

  1. import java.io.File;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import com.gdcn.bpaf.common.helper.StringHelper;
  5. import com.jacob.activeX.ActiveXComponent;
  6. import com.jacob.com.ComThread;
  7. import com.jacob.com.Dispatch;
  8. import com.jacob.com.Variant;
  9. ///
  10. / /
  11. /*

    Description: {jacob操作word类}

  12. /*
  13. /*

    Copyright: Copyright (c) 2011

  14. /*
  15. /*

    CreateDate: 2012-6-28

  16. /*
  17. /* @author Beny
  18. /* @version 1.0
  19. /*/
  20. public class JacobHelper {
  21. // word文档
  22. private Dispatch doc;
  23. // word运行程序对象
  24. private ActiveXComponent word;
  25. // 所有word文档集合
  26. private Dispatch documents;
  27. // 选定的范围或插入点
  28. private Dispatch selection;
  29. private boolean saveOnExit = true;
  30. public JacobHelper(boolean visible) throws Exception {
  31. ComThread.InitSTA();//线程启动
  32. if (word == null) {
  33. word = new ActiveXComponent("Word.Application");
  34. word.setProperty("Visible", new Variant(visible)); // 不可见打开word
  35. word.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
  36. }
  37. if (documents == null)
  38. documents = word.getProperty("Documents").toDispatch();
  39. }
  40. ///
  41. /* 设置退出时参数
  42. /*
  43. /* @param saveOnExit
  44. /* boolean true-退出时保存文件,false-退出时不保存文件
  45. /*/
  46. public void setSaveOnExit(boolean saveOnExit) {
  47. this.saveOnExit = saveOnExit;
  48. }
  49. ///
  50. /* 创建一个新的word文档
  51. /*
  52. /*/
  53. public void createNewDocument() {
  54. doc = Dispatch.call(documents, "Add").toDispatch();
  55. selection = Dispatch.get(word, "Selection").toDispatch();
  56. }
  57. ///
  58. /* 打开一个已存在的文档
  59. /*
  60. /* @param docPath
  61. /*/
  62. public void openDocument(String docPath) {
  63. // closeDocument();
  64. doc = Dispatch.call(documents, "Open", docPath).toDispatch();
  65. selection = Dispatch.get(word, "Selection").toDispatch();
  66. }
  67. ///
  68. /* 只读方式打开一个加密的文档
  69. /*
  70. /* @param docPath-文件全名
  71. /* @param pwd-密码
  72. /*/
  73. public void openDocumentOnlyRead(String docPath, String pwd)
  74. throws Exception {
  75. // closeDocument();
  76. doc = Dispatch.callN(
  77. documents,
  78. "Open",
  79. new Object[] { docPath, new Variant(false), new Variant(true),
  80. new Variant(true), pwd, "", new Variant(false) })
  81. .toDispatch();
  82. selection = Dispatch.get(word, "Selection").toDispatch();
  83. }
  84. ///
  85. /* 打开一个加密的文档
  86. /* @param docPath
  87. /* @param pwd
  88. /* @throws Exception
  89. /*/
  90. public void openDocument(String docPath, String pwd) throws Exception {
  91. // closeDocument();
  92. doc = Dispatch.callN(
  93. documents,
  94. "Open",
  95. new Object[] { docPath, new Variant(false), new Variant(false),
  96. new Variant(true), pwd }).toDispatch();
  97. selection = Dispatch.get(word, "Selection").toDispatch();
  98. }
  99. ///
  100. /* 从选定内容或插入点开始查找文本
  101. /*
  102. /* @param toFindText
  103. /* 要查找的文本
  104. /* @return boolean true-查找到并选中该文本,false-未查找到文本
  105. /*/
  106. @SuppressWarnings("static-access")
  107. public boolean find(String toFindText) {
  108. if (toFindText == null || toFindText.equals(""))
  109. return false;
  110. // 从selection所在位置开始查询
  111. Dispatch find = word.call(selection, "Find").toDispatch();
  112. // 设置要查找的内容
  113. Dispatch.put(find, "Text", toFindText);
  114. // 向前查找
  115. Dispatch.put(find, "Forward", "True");
  116. // 设置格式
  117. Dispatch.put(find, "Format", "True");
  118. // 大小写匹配
  119. Dispatch.put(find, "MatchCase", "True");
  120. // 全字匹配
  121. Dispatch.put(find, "MatchWholeWord", "false");
  122. // 查找并选中
  123. return Dispatch.call(find, "Execute").getBoolean();
  124. }
  125. ///
  126. /* 把选定选定内容设定为替换文本
  127. /*
  128. /* @param toFindText
  129. /* 查找字符串
  130. /* @param newText
  131. /* 要替换的内容
  132. /* @return
  133. /*/
  134. public boolean replaceText(String toFindText, String newText) {
  135. if (!find(toFindText))
  136. return false;
  137. Dispatch.put(selection, "Text", newText);
  138. return true;
  139. }
  140. ///
  141. /* 全局替换文本
  142. /*
  143. /* @param toFindText
  144. /* 查找字符串
  145. /* @param newText
  146. /* 要替换的内容
  147. /*/
  148. public void replaceAllText(String toFindText, String newText) {
  149. while (find(toFindText)) {
  150. Dispatch.put(selection, "Text", newText);
  151. Dispatch.call(selection, "MoveRight");
  152. }
  153. }
  154. ///
  155. /* 在当前插入点插入字符串
  156. /*
  157. /* @param newText
  158. /* 要插入的新字符串
  159. /*/
  160. public void insertText(String newText) {
  161. Dispatch.put(selection, "Text", newText);
  162. }
  163. ///
  164. /* 设置当前选定内容的字体
  165. /*
  166. /* @param boldSize
  167. /* @param italicSize
  168. /* @param underLineSize
  169. /* 下划线
  170. /* @param colorSize
  171. /* 字体颜色
  172. /* @param size
  173. /* 字体大小
  174. /* @param name
  175. /* 字体名称
  176. /* @param hidden
  177. /* 是否隐藏
  178. /*/
  179. public void setFont(boolean bold, boolean italic, boolean underLine,
  180. String colorSize, String size, String name,boolean hidden) {
  181. Dispatch font = Dispatch.get(selection, "Font").toDispatch();
  182. Dispatch.put(font, "Name", new Variant(name));
  183. Dispatch.put(font, "Bold", new Variant(bold));
  184. Dispatch.put(font, "Italic", new Variant(italic));
  185. Dispatch.put(font, "Underline", new Variant(underLine));
  186. Dispatch.put(font, "Color", colorSize);
  187. Dispatch.put(font, "Size", size);
  188. Dispatch.put(font, "Hidden", hidden);
  189. }
  190. ///
  191. /* 文件保存或另存为
  192. /*
  193. /* @param savePath
  194. /* 保存或另存为路径
  195. /*/
  196. public void save(String savePath) {
  197. Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
  198. "FileSaveAs", savePath);
  199. }
  200. ///
  201. /* 文件保存为html格式
  202. /*
  203. /* @param savePath
  204. /* @param htmlPath
  205. /*/
  206. public void saveAsHtml(String htmlPath) {
  207. Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
  208. htmlPath, new Variant(8) }, new int[1]);
  209. }
  210. ///
  211. /* 关闭文档
  212. /*
  213. /* @param val
  214. /* 0不保存修改 -1 保存修改 -2 提示是否保存修改
  215. /*/
  216. public void closeDocument(int val) {
  217. Dispatch.call(doc, "Close", new Variant(val));//注 是documents而不是doc
  218. documents = null;
  219. doc = null;
  220. }
  221. ///
  222. /* 关闭当前word文档
  223. /*
  224. /*/
  225. public void closeDocument() {
  226. if (documents != null) {
  227. Dispatch.call(documents, "Save");
  228. Dispatch.call(documents, "Close", new Variant(saveOnExit));
  229. documents = null;
  230. doc = null;
  231. }
  232. }
  233. public void closeDocumentWithoutSave() {
  234. if (documents != null) {
  235. Dispatch.call(documents, "Close", new Variant(false));
  236. documents = null;
  237. doc = null;
  238. }
  239. }
  240. ///
  241. /* 保存并关闭全部应用
  242. /*
  243. /*/
  244. public void close() {
  245. closeDocument(-1);
  246. if (word != null) {
  247. // Dispatch.call(word, "Quit");
  248. word.invoke("Quit", new Variant[] {});
  249. word = null;
  250. }
  251. selection = null;
  252. documents = null;
  253. ComThread.Release();//释放com线程。根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理
  254. }
  255. ///
  256. /* 打印当前word文档
  257. /*
  258. /*/
  259. public void printFile() {
  260. if (doc != null) {
  261. Dispatch.call(doc, "PrintOut");
  262. }
  263. }
  264. ///
  265. /* 保护当前档,如果不存在, 使用expression.Protect(Type, NoReset, Password)
  266. /*
  267. /* @param pwd
  268. /* @param type
  269. /* WdProtectionType 常量之一(int 类型,只读):
  270. /* 1-wdAllowOnlyComments 仅批注
  271. /* 2-wdAllowOnlyFormFields 仅填写窗体
  272. /* 0-wdAllowOnlyRevisions 仅修订
  273. /* -1-wdNoProtection 无保护,
  274. /* 3-wdAllowOnlyReading 只读
  275. /*
  276. /*/
  277. public void protectedWord(String pwd,String type) {
  278. String protectionType = Dispatch.get(doc, "ProtectionType").toString();
  279. if (protectionType.equals("-1")) {
  280. Dispatch.call(doc, "Protect", Integer.parseInt(type), new Variant(true),pwd);
  281. }
  282. }
  283. ///
  284. /* 解除文档保护,如果存在
  285. /*
  286. /* @param pwd
  287. /* WdProtectionType 常量之一(int 类型,只读):
  288. /* 1-wdAllowOnlyComments 仅批注
  289. /* 2-wdAllowOnlyFormFields 仅填写窗体
  290. /* 0-wdAllowOnlyRevisions 仅修订
  291. /* -1-wdNoProtection 无保护,
  292. /* 3-wdAllowOnlyReading 只读
  293. /*
  294. /*/
  295. public void unProtectedWord(String pwd) {
  296. String protectionType = Dispatch.get(doc, "ProtectionType").toString();
  297. if (!protectionType.equals("0")&&!protectionType.equals("-1")) {
  298. Dispatch.call(doc, "Unprotect", pwd);
  299. }
  300. }
  301. ///
  302. /* 返回文档的保护类型
  303. /* @return
  304. /*/
  305. public String getProtectedType(){
  306. return Dispatch.get(doc, "ProtectionType").toString();
  307. }
  308. ///
  309. /* 设置word文档安全级别
  310. /*
  311. /* @param value
  312. /* 1-msoAutomationSecurityByUI 使用“安全”对话框指定的安全设置。
  313. /* 2-msoAutomationSecurityForceDisable
  314. /* 在程序打开的所有文件中禁用所有宏,而不显示任何安全提醒。 3-msoAutomationSecurityLow
  315. /* 启用所有宏,这是启动应用程序时的默认值。
  316. /*/
  317. public void setAutomationSecurity(int value) {
  318. word.setProperty("AutomationSecurity", new Variant(value));
  319. }
  320. ///
  321. /* 在word中插入标签 labelName是标签名,labelValue是标签值
  322. /* @param labelName
  323. /* @param labelValue
  324. /*/
  325. public void insertLabelValue(String labelName,String labelValue) {
  326. Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
  327. boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();
  328. if (isExist == true) {
  329. Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();
  330. Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
  331. String bookMark1Value = Dispatch.get(range1, "Text").toString();
  332. System.out.println("书签内容:"+bookMark1Value);
  333. } else {
  334. System.out.println("当前书签不存在,重新建立!");
  335. //TODO 先插入文字,再查找选中文字,再插入标签
  336. this.insertText(labelValue);
  337. // this.find(labelValue);//查找文字,并选中
  338. this.setFont(true, true,true,"102,92,38", "20", "",true);
  339. Dispatch.call(bookMarks, "Add", labelName, selection);
  340. Dispatch.call(bookMarks, "Hidden", labelName);
  341. }
  342. }
  343. ///
  344. /* 在word中插入标签 labelName是标签名
  345. /* @param labelName
  346. /*/
  347. public void insertLabel(String labelName) {
  348. Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
  349. boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();
  350. if (isExist == true) {
  351. System.out.println("书签已存在");
  352. } else {
  353. System.out.println("建立书签:"+labelName);
  354. Dispatch.call(bookMarks, "Add", labelName, selection);
  355. }
  356. }
  357. ///
  358. /* 查找书签
  359. /* @param labelName
  360. /* @return
  361. /*/
  362. public boolean findLabel(String labelName) {
  363. Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
  364. boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();
  365. if (isExist == true) {
  366. return true;
  367. } else {
  368. System.out.println("当前书签不存在!");
  369. return false;
  370. }
  371. }
  372. ///
  373. /* 模糊查找书签,并返回准确的书签名称
  374. /* @param labelName
  375. /* @return
  376. /*/
  377. public String findLabelLike(String labelName) {
  378. Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
  379. int count = Dispatch.get(bookMarks, "Count").getInt(); // 书签数
  380. Dispatch rangeItem = null;
  381. String lname = "";
  382. for(int i=1;i<=count;i++){
  383. rangeItem = Dispatch.call(bookMarks, "Item", new Variant(i)).toDispatch();
  384. lname = Dispatch.call(rangeItem, "Name").toString();//书签名称
  385. if(lname.startsWith(labelName)){//前面匹配
  386. // return lname.replaceFirst(labelName, "");//返回后面值
  387. return lname;
  388. }
  389. }
  390. return "";
  391. }
  392. ///
  393. /* 模糊删除书签
  394. /* @param labelName
  395. /*/
  396. public void deleteLableLike(String labelName){
  397. Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
  398. int count = Dispatch.get(bookMarks, "Count").getInt(); // 书签数
  399. Dispatch rangeItem = null;
  400. String lname = "";
  401. for(int i=1;i<=count;i++){
  402. rangeItem = Dispatch.call(bookMarks, "Item", new Variant(i)).toDispatch();
  403. lname = Dispatch.call(rangeItem, "Name").toString();//书签名称
  404. if(lname.startsWith(labelName)){//前面匹配
  405. Dispatch.call(rangeItem, "Delete");
  406. count--;//书签已被删除,书签数目和当前书签都要相应减1,否则会报错:集合找不到
  407. i--;
  408. }
  409. }
  410. }
  411. ///
  412. /* 获取书签内容
  413. /* @param labelName
  414. /* @return
  415. /*/
  416. public String getLableValue(String labelName){
  417. if(this.findLabel(labelName)){
  418. Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
  419. Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();
  420. Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
  421. Dispatch font = Dispatch.get(range1, "Font").toDispatch();
  422. Dispatch.put(font, "Hidden", new Variant(false)); //显示书签内容
  423. String bookMark1Value = Dispatch.get(range1, "Text").toString();
  424. System.out.println("书签内容:"+bookMark1Value);
  425. // font = Dispatch.get(range1, "Font").toDispatch();
  426. // Dispatch.put(font, "Hidden", new Variant(true)); //隐藏书签内容
  427. return bookMark1Value;
  428. }
  429. return "";
  430. }
  431. public static void main(String[] args) throws Exception {
  432. }
  433. }

import java.io.File;

import java.util.HashMap; import java.util.Map;

import com.gdcn.bpaf.common.helper.StringHelper;

import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread;

import com.jacob.com.Dispatch; import com.jacob.com.Variant;

/// / /

/

Description: {jacob操作word类}

/

/

Copyright: Copyright (c) 2011

/

/

CreateDate: 2012-6-28

/

/ @author Beny / @version 1.0

/*/

public class JacobHelper { // word文档

private Dispatch doc;


// word运行程序对象
private ActiveXComponent word;


// 所有word文档集合

private Dispatch documents;


// 选定的范围或插入点
private Dispatch selection;


private boolean saveOnExit = true;


public JacobHelper(boolean visible) throws Exception {

    ComThread.InitSTA();//线程启动
    if (word == null) {

        word = new ActiveXComponent("Word.Application");
        word.setProperty("Visible", new Variant(visible)); // 不可见打开word

        word.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
    }

    if (documents == null)
        documents = word.getProperty("Documents").toDispatch();

}


//*/*
 /* 设置退出时参数

 /*
 /* @param saveOnExit

 /*            boolean true-退出时保存文件,false-退出时不保存文件
 /*/

public void setSaveOnExit(boolean saveOnExit) {
    this.saveOnExit = saveOnExit;

}


//*/*
 /* 创建一个新的word文档

 /*
 /*/

public void createNewDocument() {
    doc = Dispatch.call(documents, "Add").toDispatch();

    selection = Dispatch.get(word, "Selection").toDispatch();
}


//*/*

 /* 打开一个已存在的文档
 /*

 /* @param docPath
 /*/

public void openDocument(String docPath) {

// closeDocument();

    doc = Dispatch.call(documents, "Open", docPath).toDispatch();
    selection = Dispatch.get(word, "Selection").toDispatch();

}


//*/*
 /* 只读方式打开一个加密的文档

 /*
 /* @param docPath-文件全名

 /* @param pwd-密码
 /*/

public void openDocumentOnlyRead(String docPath, String pwd)
        throws Exception {

// closeDocument(); doc = Dispatch.callN(

            documents,
            "Open",

            new Object[] { docPath, new Variant(false), new Variant(true),
                    new Variant(true), pwd, "", new Variant(false) })

            .toDispatch();
    selection = Dispatch.get(word, "Selection").toDispatch();

}
//*/*

 /* 打开一个加密的文档
 /* @param docPath

 /* @param pwd
 /* @throws Exception

 /*/
public void openDocument(String docPath, String pwd) throws Exception {

// closeDocument(); doc = Dispatch.callN(

            documents,
            "Open",

            new Object[] { docPath, new Variant(false), new Variant(false),
                    new Variant(true), pwd }).toDispatch();

    selection = Dispatch.get(word, "Selection").toDispatch();
}


//*/*

 /* 从选定内容或插入点开始查找文本
 /*

 /* @param toFindText
 /*            要查找的文本

 /* @return boolean true-查找到并选中该文本,false-未查找到文本
 /*/

@SuppressWarnings("static-access")
public boolean find(String toFindText) {

    if (toFindText == null || toFindText.equals(""))
        return false;

    // 从selection所在位置开始查询
    Dispatch find = word.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", "false");

    // 查找并选中
    return Dispatch.call(find, "Execute").getBoolean();

}


//*/*
 /* 把选定选定内容设定为替换文本

 /*
 /* @param toFindText

 /*            查找字符串
 /* @param newText

 /*            要替换的内容
 /* @return

 /*/
public boolean replaceText(String toFindText, String newText) {

    if (!find(toFindText))
        return false;

    Dispatch.put(selection, "Text", newText);
    return true;

}


//*/*
 /* 全局替换文本

 /*
 /* @param toFindText

 /*            查找字符串
 /* @param newText

 /*            要替换的内容
 /*/

public void replaceAllText(String toFindText, String newText) {
    while (find(toFindText)) {

        Dispatch.put(selection, "Text", newText);
        Dispatch.call(selection, "MoveRight");

    }
}


//*/*

 /* 在当前插入点插入字符串
 /*

 /* @param newText
 /*            要插入的新字符串

 /*/
public void insertText(String newText) {

    Dispatch.put(selection, "Text", newText);
}





//*/*

 /* 设置当前选定内容的字体
 /*

 /* @param boldSize
 /* @param italicSize

 /* @param underLineSize
 /*            下划线

 /* @param colorSize
 /*            字体颜色

 /* @param size
 /*            字体大小

 /* @param name
 /*            字体名称

 /* @param hidden
 /*            是否隐藏

 /*/
public void setFont(boolean bold, boolean italic, boolean underLine,

        String colorSize, String size, String name,boolean hidden) {
    Dispatch font = Dispatch.get(selection, "Font").toDispatch();

    Dispatch.put(font, "Name", new Variant(name));
    Dispatch.put(font, "Bold", new Variant(bold));

    Dispatch.put(font, "Italic", new Variant(italic));
    Dispatch.put(font, "Underline", new Variant(underLine));

    Dispatch.put(font, "Color", colorSize);
    Dispatch.put(font, "Size", size);

    Dispatch.put(font, "Hidden", hidden);
}




//*/*
 /* 文件保存或另存为

 /*
 /* @param savePath

 /*            保存或另存为路径
 /*/

public void save(String savePath) {
    Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),

            "FileSaveAs", savePath);
}


//*/*

 /* 文件保存为html格式
 /*

 /* @param savePath
 /* @param htmlPath

 /*/
public void saveAsHtml(String htmlPath) {

    Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
            htmlPath, new Variant(8) }, new int[1]);

}


//*/*
 /* 关闭文档

 /*
 /* @param val

 /*            0不保存修改 -1 保存修改 -2 提示是否保存修改
 /*/

public void closeDocument(int val) {
    Dispatch.call(doc, "Close", new Variant(val));//注 是documents而不是doc

    documents = null;
    doc = null;

}


//*/*
 /* 关闭当前word文档

 /*
 /*/

public void closeDocument() {
    if (documents != null) {

        Dispatch.call(documents, "Save");
        Dispatch.call(documents, "Close", new Variant(saveOnExit));

        documents = null;
        doc = null;

    }
}


public void closeDocumentWithoutSave() {

    if (documents != null) {
        Dispatch.call(documents, "Close", new Variant(false));

        documents = null;
        doc = null;

    }
}


//*/*

 /* 保存并关闭全部应用
 /*

 /*/
public void close() {

    closeDocument(-1);
    if (word != null) {

// Dispatch.call(word, "Quit"); word.invoke("Quit", new Variant[] {});

        word = null;
    }

    selection = null;
    documents = null;

    ComThread.Release();//释放com线程。根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理


}
//*/*

 /* 打印当前word文档
 /*

 /*/
public void printFile() {

    if (doc != null) {
        Dispatch.call(doc, "PrintOut");

    }
}


//*/*

 /* 保护当前档,如果不存在, 使用expression.Protect(Type, NoReset, Password)
 /*

 /* @param pwd
 /* @param type

 /*            WdProtectionType 常量之一(int 类型,只读):
 /*            1-wdAllowOnlyComments  仅批注

 /*            2-wdAllowOnlyFormFields 仅填写窗体
 /*            0-wdAllowOnlyRevisions 仅修订

 /*            -1-wdNoProtection 无保护,
 /*            3-wdAllowOnlyReading 只读

 /*
 /*/

public void protectedWord(String pwd,String type) {
    String protectionType = Dispatch.get(doc, "ProtectionType").toString();

    if (protectionType.equals("-1")) {
        Dispatch.call(doc, "Protect", Integer.parseInt(type), new Variant(true),pwd);

    }
}


//*/*

 /* 解除文档保护,如果存在
 /*

 /* @param pwd
 /*            WdProtectionType 常量之一(int 类型,只读):

 /*            1-wdAllowOnlyComments  仅批注
 /*            2-wdAllowOnlyFormFields 仅填写窗体

 /*            0-wdAllowOnlyRevisions 仅修订
 /*            -1-wdNoProtection 无保护,

 /*            3-wdAllowOnlyReading 只读
 /*

 /*/
public void unProtectedWord(String pwd) {

    String protectionType = Dispatch.get(doc, "ProtectionType").toString();
    if (!protectionType.equals("0")&&!protectionType.equals("-1")) {

        Dispatch.call(doc, "Unprotect", pwd);
    }

}
//*/*

 /* 返回文档的保护类型
 /* @return

 /*/
public String getProtectedType(){

    return Dispatch.get(doc, "ProtectionType").toString();
}


//*/*

 /* 设置word文档安全级别
 /*

 /* @param value
 /*            1-msoAutomationSecurityByUI 使用“安全”对话框指定的安全设置。

 /*            2-msoAutomationSecurityForceDisable
 /*            在程序打开的所有文件中禁用所有宏,而不显示任何安全提醒。 3-msoAutomationSecurityLow

 /*            启用所有宏,这是启动应用程序时的默认值。
 /*/

public void setAutomationSecurity(int value) {
    word.setProperty("AutomationSecurity", new Variant(value));

}






//*/*

 /* 在word中插入标签 labelName是标签名,labelValue是标签值
 /* @param labelName

 /* @param labelValue
 /*/

public  void insertLabelValue(String labelName,String labelValue) {


   Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
   boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();

    if (isExist == true) {
        Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();

        Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
        String bookMark1Value = Dispatch.get(range1, "Text").toString();

          System.out.println("书签内容:"+bookMark1Value);
    } else {

        System.out.println("当前书签不存在,重新建立!");
        //TODO 先插入文字,再查找选中文字,再插入标签

        this.insertText(labelValue);

// this.find(labelValue);//查找文字,并选中

        this.setFont(true, true,true,"102,92,38", "20", "",true);
         Dispatch.call(bookMarks, "Add", labelName, selection);

         Dispatch.call(bookMarks, "Hidden", labelName);
    }

}
//*/*

 /* 在word中插入标签 labelName是标签名
 /* @param labelName

 /*/
public  void insertLabel(String labelName) {


   Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();

   boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();
    if (isExist == true) {

          System.out.println("书签已存在");
    } else {

        System.out.println("建立书签:"+labelName);
         Dispatch.call(bookMarks, "Add", labelName, selection);

    }
}   

//*/*
 /* 查找书签

 /* @param labelName
 /* @return

 /*/
public boolean findLabel(String labelName) {

   Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
   boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();

   if (isExist == true) {
          return true;

    } else {
        System.out.println("当前书签不存在!");

        return false;
    }

}
//*/*

 /* 模糊查找书签,并返回准确的书签名称
 /* @param labelName

 /* @return
 /*/

public String findLabelLike(String labelName) {
   Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();

   int count = Dispatch.get(bookMarks, "Count").getInt(); // 书签数
   Dispatch rangeItem = null;

   String lname = "";
   for(int i=1;i<=count;i++){

       rangeItem = Dispatch.call(bookMarks, "Item", new Variant(i)).toDispatch();
       lname = Dispatch.call(rangeItem, "Name").toString();//书签名称

       if(lname.startsWith(labelName)){//前面匹配

// return lname.replaceFirst(labelName, "");//返回后面值

           return lname;
       }

   }
   return "";

}
//*/*

 /* 模糊删除书签
 /* @param labelName

 /*/
public void deleteLableLike(String labelName){

    Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
   int count = Dispatch.get(bookMarks, "Count").getInt(); // 书签数

   Dispatch rangeItem = null;
   String lname = "";

   for(int i=1;i<=count;i++){
       rangeItem = Dispatch.call(bookMarks, "Item", new Variant(i)).toDispatch();

       lname = Dispatch.call(rangeItem, "Name").toString();//书签名称
       if(lname.startsWith(labelName)){//前面匹配

           Dispatch.call(rangeItem, "Delete");
           count--;//书签已被删除,书签数目和当前书签都要相应减1,否则会报错:集合找不到

           i--;
       }

   }
}

//*/*
 /* 获取书签内容

 /* @param labelName
 /* @return

 /*/
public String getLableValue(String labelName){

    if(this.findLabel(labelName)){
        Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();

        Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();
        Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();

        Dispatch font = Dispatch.get(range1, "Font").toDispatch();
        Dispatch.put(font, "Hidden", new Variant(false)); //显示书签内容

        String bookMark1Value = Dispatch.get(range1, "Text").toString();
          System.out.println("书签内容:"+bookMark1Value);

// font = Dispatch.get(range1, "Font").toDispatch(); // Dispatch.put(font, "Hidden", new Variant(true)); //隐藏书签内容

          return bookMark1Value;
    }

    return "";
}




public static void main(String[] args) throws Exception {


}   

}

采用jacob方式操作文档,经常会出现卡机的现象,所以最后采用poi方式来操作书签。若单纯的操作书签用poi方式还是比较简单的,但要操作表格、文档格式之类的还是用jacob功能比较强大。 Java代码 收藏代码

  1. InputStream input = null;
  2. File docFile = new File( fileName );
  3. HWPFDocument document = null;
  4. try{
  5. input = new FileInputStream(docFile);//加载 doc 文档
  6. document = new HWPFDocument(input);//文件流方式创建hwpf
  7. Bookmarks bookmarks = document.getBookmarks();//文档书签
  8. for(int i=0,length=bookmarks.getBookmarksCount();i<length;i++){
  9. bookmarkName = bookmarks.getBookmark(i).getName();
  10. //.....
  11. }
  12. }catch( Exception e){
  13. }finally{
  14. if( null != input )
  15. input.close();
  16. }

InputStream input = null;

File docFile = new File( fileName ); HWPFDocument document = null;

try{ input = new FileInputStream(docFile);//加载 doc 文档

document = new HWPFDocument(input);//文件流方式创建hwpf
Bookmarks bookmarks =  document.getBookmarks();//文档书签

for(int i=0,length=bookmarks.getBookmarksCount();i<length;i++){
    bookmarkName = bookmarks.getBookmark(i).getName();

    //.....
}

}catch( Exception e){

}finally{

if( null != input )
        input.close();

}

希望本站内容对您有点用处,有什么疑问或建议请在后面留言评论
转载请注明作者(RobinChia)和出处 It so life ,请勿用于任何商业用途