1. import com.jacob.activeX.ActiveXComponent;
  2. import com.jacob.com.Dispatch;
  3. import com.jacob.com.Variant;
  4. /**
  5. * jacob操作MSword类
  6. * @author
  7. */
  8. public class WordBean {
  9. // word文档
  10. private Dispatch doc;
  11. // word运行程序对象
  12. private ActiveXComponent word;
  13. // 所有word文档集合
  14. private Dispatch documents;
  15. // 选定的范围或插入点
  16. private Dispatch selection;
  17. private boolean saveOnExit = true;
  18. public WordBean()throws Exception{
  19. if (word == null) {
  20. word = new ActiveXComponent("Word.Application");
  21. word.setProperty("Visible", new Variant(false));    //不可见打开word
  22. word.setProperty("AutomationSecurity", new Variant(3)); //禁用宏
  23. }
  24. if (documents == null)
  25. documents = word.getProperty("Documents").toDispatch();
  26. }
  27. /**
  28. * 设置退出时参数
  29. *
  30. * @param saveOnExit
  31. *            boolean true-退出时保存文件,false-退出时不保存文件
  32. */
  33. public void setSaveOnExit(boolean saveOnExit) {
  34. this.saveOnExit = saveOnExit;
  35. }
  36. /**
  37. * 创建一个新的word文档
  38. *
  39. */
  40. public void createNewDocument() {
  41. doc = Dispatch.call(documents, "Add").toDispatch();
  42. selection = Dispatch.get(word, "Selection").toDispatch();
  43. }
  44. /**
  45. * 打开一个已存在的文档
  46. *
  47. * @param docPath
  48. */
  49. public void openDocument(String docPath) {
  50. closeDocument();
  51. doc = Dispatch.call(documents, "Open", docPath).toDispatch();
  52. selection = Dispatch.get(word, "Selection").toDispatch();
  53. }
  54. /**
  55. * 打开一个保护文档,
  56. * @param docPath-文件全名
  57. * @param pwd-密码
  58. */
  59. public void openDocumentOnlyRead(String docPath, String pwd)throws Exception {
  60. closeDocument();
  61. //      doc = Dispatch.invoke(documents, "Open", Dispatch.Method,
  62. //              new Object[]{docPath, new Variant(false), new Variant(true), new Variant(true), pwd},
  63. //              new int[1]).toDispatch();//打开word文件
  64. doc =  Dispatch.callN(documents, "Open", new Object[]{docPath, new Variant(false),
  65. new Variant(true), new Variant(true), pwd, "", new Variant(false)}).toDispatch();
  66. selection = Dispatch.get(word, "Selection").toDispatch();
  67. }
  68. public void openDocument(String docPath, String pwd)throws Exception {
  69. closeDocument();
  70. doc =  Dispatch.callN(documents, "Open", new Object[]{docPath, new Variant(false),
  71. new Variant(false), new Variant(true), pwd}).toDispatch();
  72. selection = Dispatch.get(word, "Selection").toDispatch();
  73. }
  74. /**
  75. * 把选定的内容或插入点向上移动
  76. *
  77. * @param pos
  78. *            移动的距离
  79. */
  80. public void moveUp(int pos) {
  81. if (selection == null)
  82. selection = Dispatch.get(word, "Selection").toDispatch();
  83. for (int i = 0; i < pos; i++)
  84. Dispatch.call(selection, "MoveUp");
  85. }
  86. /**
  87. * 把选定的内容或者插入点向下移动
  88. *
  89. * @param pos
  90. *            移动的距离
  91. */
  92. public void moveDown(int pos) {
  93. if (selection == null)
  94. selection = Dispatch.get(word, "Selection").toDispatch();
  95. for (int i = 0; i < pos; i++)
  96. Dispatch.call(selection, "MoveDown");
  97. }
  98. /**
  99. * 把选定的内容或者插入点向左移动
  100. *
  101. * @param pos
  102. *            移动的距离
  103. */
  104. public void moveLeft(int pos) {
  105. if (selection == null)
  106. selection = Dispatch.get(word, "Selection").toDispatch();
  107. for (int i = 0; i < pos; i++) {
  108. Dispatch.call(selection, "MoveLeft");
  109. }
  110. }
  111. /**
  112. * 把选定的内容或者插入点向右移动
  113. *
  114. * @param pos
  115. *            移动的距离
  116. */
  117. public void moveRight(int pos) {
  118. if (selection == null)
  119. selection = Dispatch.get(word, "Selection").toDispatch();
  120. for (int i = 0; i < pos; i++)
  121. Dispatch.call(selection, "MoveRight");
  122. }
  123. /**
  124. * 把插入点移动到文件首位置
  125. *
  126. */
  127. public void moveStart() {
  128. if (selection == null)
  129. selection = Dispatch.get(word, "Selection").toDispatch();
  130. Dispatch.call(selection, "HomeKey", new Variant(6));
  131. }
  132. /**
  133. * 从选定内容或插入点开始查找文本
  134. *
  135. * @param toFindText
  136. *            要查找的文本
  137. * @return boolean true-查找到并选中该文本,false-未查找到文本
  138. */
  139. @SuppressWarnings("static-access")
  140. public boolean find(String toFindText) {
  141. if (toFindText == null || toFindText.equals(""))
  142. return false;
  143. // 从selection所在位置开始查询
  144. Dispatch find = word.call(selection, "Find").toDispatch();
  145. // 设置要查找的内容
  146. Dispatch.put(find, "Text", toFindText);
  147. // 向前查找
  148. Dispatch.put(find, "Forward", "True");
  149. // 设置格式
  150. Dispatch.put(find, "Format", "True");
  151. // 大小写匹配
  152. Dispatch.put(find, "MatchCase", "True");
  153. // 全字匹配
  154. Dispatch.put(find, "MatchWholeWord", "True");
  155. // 查找并选中
  156. return Dispatch.call(find, "Execute").getBoolean();
  157. }
  158. /**
  159. * 把选定选定内容设定为替换文本
  160. *
  161. * @param toFindText
  162. *            查找字符串
  163. * @param newText
  164. *            要替换的内容
  165. * @return
  166. */
  167. public boolean replaceText(String toFindText, String newText) {
  168. if (!find(toFindText))
  169. return false;
  170. Dispatch.put(selection, "Text", newText);
  171. return true;
  172. }
  173. /**
  174. * 全局替换文本
  175. *
  176. * @param toFindText
  177. *            查找字符串
  178. * @param newText
  179. *            要替换的内容
  180. */
  181. public void replaceAllText(String toFindText, String newText) {
  182. while (find(toFindText)) {
  183. Dispatch.put(selection, "Text", newText);
  184. Dispatch.call(selection, "MoveRight");
  185. }
  186. }
  187. /**
  188. * 在当前插入点插入字符串
  189. *
  190. * @param newText
  191. *            要插入的新字符串
  192. */
  193. public void insertText(String newText) {
  194. Dispatch.put(selection, "Text", newText);
  195. }
  196. /**
  197. *
  198. * @param toFindText
  199. *            要查找的字符串
  200. * @param imagePath
  201. *            图片路径
  202. * @return
  203. */
  204. public boolean replaceImage(String toFindText, String imagePath) {
  205. if (!find(toFindText))
  206. return false;
  207. Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
  208. "AddPicture", imagePath);
  209. return true;
  210. }
  211. /**
  212. * 全局替换图片
  213. *
  214. * @param toFindText
  215. *            查找字符串
  216. * @param imagePath
  217. *            图片路径
  218. */
  219. public void replaceAllImage(String toFindText, String imagePath) {
  220. while (find(toFindText)) {
  221. Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
  222. "AddPicture", imagePath);
  223. Dispatch.call(selection, "MoveRight");
  224. }
  225. }
  226. /**
  227. * 在当前插入点插入图片
  228. *
  229. * @param imagePath
  230. *            图片路径
  231. */
  232. public void insertImage(String imagePath) {
  233. Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
  234. "AddPicture", imagePath);
  235. }
  236. /**
  237. * 合并单元格
  238. *
  239. * @param tableIndex
  240. * @param fstCellRowIdx
  241. * @param fstCellColIdx
  242. * @param secCellRowIdx
  243. * @param secCellColIdx
  244. */
  245. public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
  246. int secCellRowIdx, int secCellColIdx) {
  247. // 所有表格
  248. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  249. // 要填充的表格
  250. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  251. .toDispatch();
  252. Dispatch fstCell = Dispatch.call(table, "Cell",
  253. new Variant(fstCellRowIdx), new Variant(fstCellColIdx))
  254. .toDispatch();
  255. Dispatch secCell = Dispatch.call(table, "Cell",
  256. new Variant(secCellRowIdx), new Variant(secCellColIdx))
  257. .toDispatch();
  258. Dispatch.call(fstCell, "Merge", secCell);
  259. }
  260. /**
  261. * 在指定的单元格里填写数据
  262. *
  263. * @param tableIndex
  264. * @param cellRowIdx
  265. * @param cellColIdx
  266. * @param txt
  267. */
  268. public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
  269. String txt) {
  270. // 所有表格
  271. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  272. // 要填充的表格
  273. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  274. .toDispatch();
  275. Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
  276. new Variant(cellColIdx)).toDispatch();
  277. Dispatch.call(cell, "Select");
  278. Dispatch.put(selection, "Text", txt);
  279. }
  280. /**
  281. * 获得指定的单元格里数据
  282. *
  283. * @param tableIndex
  284. * @param cellRowIdx
  285. * @param cellColIdx
  286. * @return
  287. */
  288. public String getTxtFromCell(int tableIndex, int cellRowIdx, int cellColIdx) {
  289. // 所有表格
  290. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  291. // 要填充的表格
  292. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  293. .toDispatch();
  294. Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
  295. new Variant(cellColIdx)).toDispatch();
  296. Dispatch.call(cell, "Select");
  297. String ret = "";
  298. ret = Dispatch.get(selection, "Text").toString();
  299. ret = ret.substring(0, ret.length()-1); //去掉最后的回车符;
  300. return ret;
  301. }
  302. /**
  303. * 在当前文档拷贝剪贴板数据
  304. * @param pos
  305. */
  306. public void pasteExcelSheet(String pos) {
  307. moveStart();
  308. if (this.find(pos)) {
  309. Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
  310. Dispatch.call(textRange, "Paste");
  311. }
  312. }
  313. /**
  314. * 在当前文档指定的位置拷贝表格
  315. *
  316. * @param pos
  317. *            当前文档指定的位置
  318. * @param tableIndex
  319. *            被拷贝的表格在word文档中所处的位置
  320. */
  321. public void copyTable(String pos, int tableIndex) {
  322. // 所有表格
  323. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  324. // 要填充的表格
  325. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  326. .toDispatch();
  327. Dispatch range = Dispatch.get(table, "Range").toDispatch();
  328. Dispatch.call(range, "Copy");
  329. if (this.find(pos)) {
  330. Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
  331. Dispatch.call(textRange, "Paste");
  332. }
  333. }
  334. /**
  335. * 在当前文档指定的位置拷贝来自另一个文档中的表格
  336. *
  337. * @param anotherDocPath
  338. *            另一个文档的磁盘路径
  339. * @param tableIndex
  340. *            被拷贝的表格在另一格文档中的位置
  341. * @param pos
  342. *            当前文档指定的位置
  343. */
  344. public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,
  345. String pos) {
  346. Dispatch doc2 = null;
  347. try {
  348. doc2 = Dispatch.call(documents, "Open", anotherDocPath)
  349. .toDispatch();
  350. // 所有表格
  351. Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();
  352. // 要填充的表格
  353. Dispatch table = Dispatch.call(tables, "Item",
  354. new Variant(tableIndex)).toDispatch();
  355. Dispatch range = Dispatch.get(table, "Range").toDispatch();
  356. Dispatch.call(range, "Copy");
  357. if (this.find(pos)) {
  358. Dispatch textRange = Dispatch.get(selection, "Range")
  359. .toDispatch();
  360. Dispatch.call(textRange, "Paste");
  361. }
  362. } catch (Exception e) {
  363. e.printStackTrace();
  364. } finally {
  365. if (doc2 != null) {
  366. Dispatch.call(doc2, "Close", new Variant(saveOnExit));
  367. doc2 = null;
  368. }
  369. }
  370. }
  371. /**
  372. * 在当前文档指定的位置拷贝来自另一个文档中的图片
  373. *
  374. * @param anotherDocPath 另一个文档的磁盘路径
  375. * @param shapeIndex 被拷贝的图片在另一格文档中的位置
  376. * @param pos 当前文档指定的位置
  377. */
  378. public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,
  379. String pos) {
  380. Dispatch doc2 = null;
  381. try {
  382. doc2 = Dispatch.call(documents, "Open", anotherDocPath)
  383. .toDispatch();
  384. Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch();
  385. Dispatch shape = Dispatch.call(shapes, "Item",
  386. new Variant(shapeIndex)).toDispatch();
  387. Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();
  388. Dispatch.call(imageRange, "Copy");
  389. if (this.find(pos)) {
  390. Dispatch textRange = Dispatch.get(selection, "Range")
  391. .toDispatch();
  392. Dispatch.call(textRange, "Paste");
  393. }
  394. } catch (Exception e) {
  395. e.printStackTrace();
  396. } finally {
  397. if (doc2 != null) {
  398. Dispatch.call(doc2, "Close", new Variant(saveOnExit));
  399. doc2 = null;
  400. }
  401. }
  402. }
  403. /**
  404. * 创建表格
  405. *
  406. * @param pos
  407. *            位置
  408. * @param cols
  409. *            列数
  410. * @param rows
  411. *            行数
  412. */
  413. public void createTable(String pos, int numCols, int numRows) {
  414. if (find(pos)) {
  415. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  416. Dispatch range = Dispatch.get(selection, "Range").toDispatch();
  417. @SuppressWarnings("unused")
  418. Dispatch newTable = Dispatch.call(tables, "Add", range,
  419. new Variant(numRows), new Variant(numCols)).toDispatch();
  420. Dispatch.call(selection, "MoveRight");
  421. } else {
  422. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  423. Dispatch range = Dispatch.get(selection, "Range").toDispatch();
  424. @SuppressWarnings("unused")
  425. Dispatch newTable = Dispatch.call(tables, "Add", range,
  426. new Variant(numRows), new Variant(numCols)).toDispatch();
  427. Dispatch.call(selection, "MoveRight");
  428. }
  429. }
  430. /**
  431. * 在指定行前面增加行
  432. *
  433. * @param tableIndex
  434. *            word文件中的第N张表(从1开始)
  435. * @param rowIndex
  436. *            指定行的序号(从1开始)
  437. */
  438. public void addTableRow(int tableIndex, int rowIndex) {
  439. // 所有表格
  440. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  441. // 要填充的表格
  442. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  443. .toDispatch();
  444. // 表格的所有行
  445. Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
  446. Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex))
  447. .toDispatch();
  448. Dispatch.call(rows, "Add", new Variant(row));
  449. }
  450. /**
  451. * 在第1行前增加一行
  452. *
  453. * @param tableIndex
  454. *  word文档中的第N张表(从1开始)
  455. */
  456. public void addFirstTableRow(int tableIndex) {
  457. // 所有表格
  458. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  459. // 要填充的表格
  460. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  461. .toDispatch();
  462. // 表格的所有行
  463. Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
  464. Dispatch row = Dispatch.get(rows, "First").toDispatch();
  465. Dispatch.call(rows, "Add", new Variant(row));
  466. }
  467. /**
  468. * 在最后1行前增加一行
  469. *
  470. * @param tableIndex
  471. *            word文档中的第N张表(从1开始)
  472. */
  473. public void addLastTableRow(int tableIndex) {
  474. // 所有表格
  475. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  476. // 要填充的表格
  477. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  478. .toDispatch();
  479. // 表格的所有行
  480. Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
  481. Dispatch row = Dispatch.get(rows, "Last").toDispatch();
  482. Dispatch.call(rows, "Add", new Variant(row));
  483. }
  484. /**
  485. * 增加一行
  486. *
  487. * @param tableIndex
  488. *            word文档中的第N张表(从1开始)
  489. */
  490. public void addRow(int tableIndex) {
  491. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  492. // 要填充的表格
  493. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  494. .toDispatch();
  495. // 表格的所有行
  496. Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
  497. Dispatch.call(rows, "Add");
  498. }
  499. /**
  500. * 增加一列
  501. *
  502. * @param tableIndex
  503. *            word文档中的第N张表(从1开始)
  504. */
  505. public void addCol(int tableIndex) {
  506. // 所有表格
  507. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  508. // 要填充的表格
  509. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  510. .toDispatch();
  511. // 表格的所有行
  512. Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
  513. Dispatch.call(cols, "Add").toDispatch();
  514. Dispatch.call(cols, "AutoFit");
  515. }
  516. /**
  517. * 在指定列前面增加表格的列
  518. *
  519. * @param tableIndex
  520. *            word文档中的第N张表(从1开始)
  521. * @param colIndex
  522. *            制定列的序号 (从1开始)
  523. */
  524. public void addTableCol(int tableIndex, int colIndex) {
  525. // 所有表格
  526. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  527. // 要填充的表格
  528. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  529. .toDispatch();
  530. // 表格的所有行
  531. Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
  532. System.out.println(Dispatch.get(cols, "Count"));
  533. Dispatch col = Dispatch.call(cols, "Item", new Variant(colIndex))
  534. .toDispatch();
  535. // Dispatch col = Dispatch.get(cols, "First").toDispatch();
  536. Dispatch.call(cols, "Add", col).toDispatch();
  537. Dispatch.call(cols, "AutoFit");
  538. }
  539. /**
  540. * 在第1列前增加一列
  541. *
  542. * @param tableIndex
  543. *            word文档中的第N张表(从1开始)
  544. */
  545. public void addFirstTableCol(int tableIndex) {
  546. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  547. // 要填充的表格
  548. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  549. .toDispatch();
  550. // 表格的所有行
  551. Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
  552. Dispatch col = Dispatch.get(cols, "First").toDispatch();
  553. Dispatch.call(cols, "Add", col).toDispatch();
  554. Dispatch.call(cols, "AutoFit");
  555. }
  556. /**
  557. * 在最后一列前增加一列
  558. *
  559. * @param tableIndex
  560. *            word文档中的第N张表(从1开始)
  561. */
  562. public void addLastTableCol(int tableIndex) {
  563. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  564. // 要填充的表格
  565. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  566. .toDispatch();
  567. // 表格的所有行
  568. Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
  569. Dispatch col = Dispatch.get(cols, "Last").toDispatch();
  570. Dispatch.call(cols, "Add", col).toDispatch();
  571. Dispatch.call(cols, "AutoFit");
  572. }
  573. /**
  574. * 自动调整表格
  575. *
  576. */
  577. @SuppressWarnings("deprecation")
  578. public void autoFitTable() {
  579. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  580. int count = Dispatch.get(tables, "Count").toInt();
  581. for (int i = 0; i < count; i++) {
  582. Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
  583. .toDispatch();
  584. Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
  585. Dispatch.call(cols, "AutoFit");
  586. }
  587. }
  588. /**
  589. * 调用word里的宏以调整表格的宽度,其中宏保存在document下
  590. *
  591. */
  592. @SuppressWarnings("deprecation")
  593. public void callWordMacro() {
  594. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  595. int count = Dispatch.get(tables, "Count").toInt();
  596. Variant vMacroName = new Variant("Normal.NewMacros.tableFit");
  597. @SuppressWarnings("unused")
  598. Variant vParam = new Variant("param1");
  599. @SuppressWarnings("unused")
  600. Variant para[] = new Variant[] { vMacroName };
  601. for (int i = 0; i < count; i++) {
  602. Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
  603. .toDispatch();
  604. Dispatch.call(table, "Select");
  605. Dispatch.call(word, "Run", "tableFitContent");
  606. }
  607. }
  608. /**
  609. * 设置当前选定内容的字体
  610. *
  611. * @param boldSize
  612. * @param italicSize
  613. * @param underLineSize
  614. *            下划线
  615. * @param colorSize
  616. *            字体颜色
  617. * @param size
  618. *            字体大小
  619. * @param name
  620. *            字体名称
  621. */
  622. public void setFont(boolean bold, boolean italic, boolean underLine,
  623. String colorSize, String size, String name) {
  624. Dispatch font = Dispatch.get(selection, "Font").toDispatch();
  625. Dispatch.put(font, "Name", new Variant(name));
  626. Dispatch.put(font, "Bold", new Variant(bold));
  627. Dispatch.put(font, "Italic", new Variant(italic));
  628. Dispatch.put(font, "Underline", new Variant(underLine));
  629. Dispatch.put(font, "Color", colorSize);
  630. Dispatch.put(font, "Size", size);
  631. }
  632. /**
  633. * 设置单元格被选中
  634. *
  635. * @param tableIndex
  636. * @param cellRowIdx
  637. * @param cellColIdx
  638. */
  639. public void setTableCellSelected(int tableIndex, int cellRowIdx, int cellColIdx){
  640. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  641. Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
  642. .toDispatch();
  643. Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
  644. new Variant(cellColIdx)).toDispatch();
  645. Dispatch.call(cell, "Select");
  646. }
  647. /**
  648. * 设置选定单元格的垂直对起方式, 请使用setTableCellSelected选中一个单元格
  649. * @param align 0-顶端, 1-居中, 3-底端
  650. */
  651. public void setCellVerticalAlign(int verticalAlign){
  652. Dispatch cells = Dispatch.get(selection, "Cells").toDispatch();
  653. Dispatch.put(cells, "VerticalAlignment", new Variant(verticalAlign));
  654. }
  655. /**
  656. * 设置当前文档中所有表格水平居中方式及其它一些格式,用在将word文件转化为html中,针对申报表
  657. */
  658. @SuppressWarnings("deprecation")
  659. public void setApplyTableFormat(){
  660. Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
  661. int tabCount = Integer.valueOf(Dispatch.get(tables, "Count").toString());   //System.out.println(tabCount);
  662. System.out.println("*******************************************************");
  663. for(int i=1; i<=tabCount; i++){
  664. Dispatch table = Dispatch.call(tables, "Item", new Variant(i)).toDispatch();
  665. Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
  666. if(i==1){
  667. Dispatch.put(rows, "Alignment", new Variant(2));    //1-居中,2-Right
  668. continue ;
  669. }
  670. Dispatch.put(rows, "Alignment", new Variant(1));    //1-居中
  671. Dispatch.call(table, "AutoFitBehavior", new Variant(1));//设置自动调整表格方式,1-根据窗口自动调整
  672. Dispatch.put(table, "PreferredWidthType", new Variant(1));
  673. Dispatch.put(table, "PreferredWidth", new Variant(700));
  674. System.out.println(Dispatch.get(rows, "HeightRule").toString());
  675. Dispatch.put(rows, "HeightRule", new Variant(1));   //0-自动wdRowHeightAuto,1-最小值wdRowHeightAtLeast, 2-固定wdRowHeightExactly
  676. Dispatch.put(rows, "Height", new Variant(0.04*28.35));
  677. //int oldAlign = Integer.valueOf(Dispatch.get(rows, "Alignment").toString());
  678. //System.out.println("Algin:" + oldAlign);
  679. }
  680. }
  681. /**
  682. * 设置段落格式
  683. *
  684. * @param alignment
  685. *          0-左对齐, 1-右对齐, 2-右对齐, 3-两端对齐, 4-分散对齐
  686. * @param lineSpaceingRule
  687. * @param lineUnitBefore
  688. * @param lineUnitAfter
  689. * @param characterUnitFirstLineIndent
  690. */
  691. public void setParagraphsProperties(int alignment, int lineSpaceingRule,
  692. int lineUnitBefore, int lineUnitAfter, int characterUnitFirstLineIndent){
  693. Dispatch paragraphs = Dispatch.get(selection, "Paragraphs").toDispatch();
  694. Dispatch.put(paragraphs, "Alignment", new Variant(alignment));              //对齐方式
  695. Dispatch.put(paragraphs, "LineSpacingRule", new Variant(lineSpaceingRule)); //行距
  696. Dispatch.put(paragraphs, "LineUnitBefore", new Variant(lineUnitBefore));    //段前
  697. Dispatch.put(paragraphs, "LineUnitAfter", new Variant(lineUnitAfter));      //段后
  698. Dispatch.put(paragraphs, "CharacterUnitFirstLineIndent",
  699. new Variant(characterUnitFirstLineIndent));                         //首行缩进字符数
  700. }
  701. /**
  702. * 设置当前段落格式, 使用前,请先选中段落
  703. */
  704. public void getParagraphsProperties(){
  705. Dispatch paragraphs = Dispatch.get(selection, "Paragraphs").toDispatch();
  706. String val = Dispatch.get(paragraphs, "LineSpacingRule").toString();    //行距
  707. val = Dispatch.get(paragraphs, "Alignment").toString();         //对齐方式
  708. val = Dispatch.get(paragraphs, "LineUnitBefore").toString();    //段前行数
  709. val = Dispatch.get(paragraphs, "LineUnitAfter").toString();     //段后行数
  710. val = Dispatch.get(paragraphs, "FirstLineIndent").toString();   //首行缩进
  711. val = Dispatch.get(paragraphs, "CharacterUnitFirstLineIndent").toString();  //首行缩进字符数
  712. }
  713. /**
  714. * 文件保存或另存为
  715. *
  716. * @param savePath
  717. *            保存或另存为路径
  718. */
  719. public void save(String savePath) {
  720. Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
  721. "FileSaveAs", savePath);
  722. }
  723. /**
  724. * 文件保存为html格式
  725. *
  726. * @param savePath
  727. * @param htmlPath
  728. */
  729. public void saveAsHtml(String htmlPath){
  730. Dispatch.invoke(doc,"SaveAs", Dispatch.Method,
  731. new Object[]{htmlPath, new Variant(8)}, new int[1]);
  732. }
  733. /**
  734. * 关闭文档
  735. *@param val 0不保存修改 -1 保存修改 -2 提示是否保存修改
  736. */
  737. public void closeDocument(int val) {
  738. Dispatch.call(doc, "Close", new Variant(val));
  739. doc = null;
  740. }
  741. /**
  742. * 关闭当前word文档
  743. *
  744. */
  745. public void closeDocument() {
  746. if (doc != null) {
  747. Dispatch.call(doc, "Save");
  748. Dispatch.call(doc, "Close", new Variant(saveOnExit));
  749. doc = null;
  750. }
  751. }
  752. public void closeDocumentWithoutSave(){
  753. if (doc != null) {
  754. Dispatch.call(doc, "Close", new Variant(false));
  755. doc = null;
  756. }
  757. }
  758. /**
  759. * 关闭全部应用
  760. *
  761. */
  762. public void close() {
  763. //closeDocument();
  764. if (word != null) {
  765. Dispatch.call(word, "Quit");
  766. word = null;
  767. }
  768. selection = null;
  769. documents = null;
  770. }
  771. /**
  772. * 打印当前word文档
  773. *
  774. */
  775. public void printFile() {
  776. if (doc != null) {
  777. Dispatch.call(doc, "PrintOut");
  778. }
  779. }
  780. /**
  781. * 保护当前档,如果不存在, 使用expression.Protect(Type, NoReset, Password)
  782. *
  783. * @param pwd
  784. * WdProtectionType 可以是下列 WdProtectionType 常量之一:
  785. *      1-wdAllowOnlyComments, 2-wdAllowOnlyFormFields, 0-wdAllowOnlyRevisions,
  786. *      -1-wdNoProtection, 3-wdAllowOnlyReading
  787. *
  788. * 使用参照 main1()
  789. */
  790. public void protectedWord(String pwd){
  791. String protectionType = Dispatch.get(doc, "ProtectionType").toString();
  792. if(protectionType.equals("-1")){
  793. Dispatch.call(doc, "Protect", new Variant(3), new Variant(true), pwd);
  794. }
  795. }
  796. /**
  797. * 解除文档保护,如果存在
  798. * @param pwd
  799. * WdProtectionType 常量之一(Long 类型,只读):
  800. *      1-wdAllowOnlyComments,2-wdAllowOnlyFormFields、
  801. *      0-wdAllowOnlyRevisions,-1-wdNoProtection, 3-wdAllowOnlyReading
  802. *
  803. *      使用参照 main1()
  804. */
  805. public void unProtectedWord(String pwd){
  806. String protectionType = Dispatch.get(doc, "ProtectionType").toString();
  807. if(protectionType.equals("3")){
  808. Dispatch.call(doc, "Unprotect", pwd);
  809. }
  810. }
  811. /**
  812. * 设置word文档安全级别
  813. * @param value
  814. *      1-msoAutomationSecurityByUI  使用“安全”对话框指定的安全设置。
  815. *      2-msoAutomationSecurityForceDisable  在程序打开的所有文件中禁用所有宏,而不显示任何安全提醒。
  816. *      3-msoAutomationSecurityLow  启用所有宏,这是启动应用程序时的默认值。
  817. */
  818. public void setAutomationSecurity(int value){
  819. word.setProperty("AutomationSecurity", new Variant(value));
  820. }
  821. /**
  822. * 读取文档中第paragraphsIndex段文字的内容;
  823. * @param paragraphsIndex
  824. * @return
  825. */
  826. public String getParagraphs(int paragraphsIndex){
  827. String ret = "";
  828. Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch(); // 所有段落
  829. int paragraphCount = Dispatch.get(paragraphs, "Count").getInt();            // 一共的段落数
  830. Dispatch paragraph = null;
  831. Dispatch range = null;
  832. if(paragraphCount > paragraphsIndex && 0 < paragraphsIndex){
  833. paragraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphsIndex)).toDispatch();
  834. range = Dispatch.get(paragraph, "Range").toDispatch();
  835. ret = Dispatch.get(range, "Text").toString();
  836. }
  837. return ret;
  838. }
  839. /**
  840. * 设置页眉文字
  841. * @param cont
  842. * @return
  843. *
  844. * Sub AddHeaderText()
  845. * '设置页眉或页脚中的文字
  846. * '由 Headers、Footers 和 HeaderFooter 属性返回 HeaderFooter 对象。下列示例更改当前页眉中的文字。
  847. *  With ActiveDocument.ActiveWindow.View
  848. *      .SeekView = wdSeekCurrentPageHeader
  849. *      Selection.HeaderFooter.Range.Text = "Header text"
  850. *      .SeekView = wdSeekMainDocument
  851. *  End With
  852. * End Sub
  853. */
  854. public void setHeaderContent(String cont){
  855. Dispatch activeWindow = Dispatch.get(doc, "ActiveWindow").toDispatch();
  856. Dispatch view = Dispatch.get(activeWindow, "View").toDispatch();
  857. //Dispatch seekView = Dispatch.get(view, "SeekView").toDispatch();
  858. Dispatch.put(view, "SeekView", new Variant(9));         //wdSeekCurrentPageHeader-9
  859. Dispatch headerFooter = Dispatch.get(selection, "HeaderFooter").toDispatch();
  860. Dispatch range = Dispatch.get(headerFooter, "Range").toDispatch();
  861. Dispatch.put(range, "Text", new Variant(cont));
  862. //String content = Dispatch.get(range, "Text").toString();
  863. Dispatch font = Dispatch.get(range, "Font").toDispatch();
  864. Dispatch.put(font, "Name", new Variant("楷体_GB2312"));
  865. Dispatch.put(font, "Bold", new Variant(true));
  866. //Dispatch.put(font, "Italic", new Variant(true));
  867. //Dispatch.put(font, "Underline", new Variant(true));
  868. Dispatch.put(font, "Size", 9);
  869. Dispatch.put(view, "SeekView", new Variant(0));         //wdSeekMainDocument-0恢复视图;
  870. }
  871. public static void main(String[] args)throws Exception{
  872. WordBean word = new WordBean();
  873. word.openDocument("D:/竞价平台.doc");
  874. word.setHeaderContent("*****************88设置页眉内容11111111111111111!");
  875. //word.unProtectedWord("1qaz");
  876. //word.protectedWord("123");
  877. System.out.print(word.getParagraphs(3));
  878. word.closeDocument();
  879. word.close();
  880. }
  881. }

最新文章

  1. JFinal 的初始化
  2. [转]Python的ASCII, GB2312, Unicode , UTF-8
  3. 怎么配置Java环境变量?
  4. Mac常用基本命令/常用Git命令
  5. TYVJ P1067 合唱队形 Label:上升子序列?
  6. Chrome模拟手机浏览网页
  7. XML中的Xpath解析的例子
  8. Windows.document对象
  9. (转)使用 .NET 的 RNGCryptoServiceProvider 生成随机数
  10. 我的第一个Servlet
  11. JS对文档进行操作
  12. iOS开发设置关于tabBar和navigationBar以及item中的一些全局属性
  13. 【BZOJ4196】【NOI2015】软件包管理器(树链剖分,线段树)
  14. Linux命令之常用篇
  15. 1、roboguide新建工程文件
  16. C# 处理PPT水印(二)——去除水印效果(文本水印、图片水印)
  17. 官网类原型模板分享——Apple
  18. 遇到问题----linux-----linux 打开文件数 too many open files 解决方法
  19. day5模块学习--configparser模块
  20. CSS边框长度控制

热门文章

  1. csu1510 Happy Robot 递推
  2. MySQL&lt;数据库和表的基本操作&gt;
  3. 解决IE中img.onload失效的方法
  4. HTML节点树
  5. redis学习之集群报错Node is not empty
  6. MVC AJAX Pager Helper
  7. 利用border制作三角形原理
  8. java框架----&gt;quartz整合spring(一)
  9. net 中的一些知识
  10. 新增form表单,post提交.2