jacob语法总结
1、Dispatch.get(ds, “a1”);返回Variant类型,获取ds对象的a1属性,通过to…()和get...()方法可以转换为java的很多类型
2、Dispatch.put(ds, “a1”, …);设置ds对象a1属性,具体参数为…指定
3、ActiveXComponent有setProperty(“a1”, …)和getProperty(“a1”)方法,比Dispatch的put和get方法方便!
4、Dispatch.invoke(ds, “a3”, a4, a5, a6).toDispatch(); 说明:ds为要执行操作的对象,a3为要执行的操作名称;a4一般为Dispatch.Method、Dispatch.Put、Dispatch.Get三种,正是这三种指定让此方法可以执行put、set、call同样操作;a5为一个对象数组,形如:new Object[]{},一般的当Method时为三个参数,Get时没有参数,Put是为两个参数;a6一般为new int[1]
5、Dispatch.call(ds, “a1”, …) .toDispatch();和invoke差不多,执行a1名称的操作,少了invoke中的a4和a6参数;…和invoke中newObject[]{}中参数一样
6、所以Dispatch.call()和Dispatch.invoke()方法可以执行Dispatch.put()和Dispatch.set()的操作,反之不可以
7、Word中的属性参数有:
Documents:所有文档
Open:打开文档
ActiveXComponent.Visible:设置编辑器是否可见
![](/qrcode.jpg)
Tables:获得所有的表格
Bookmarks:所有标签
Selection:光标所在处或选中的区域
select:选中
typeParagraph:设置为一个段落
ParagraphFormat:段落格式,用alignment设置
alignment:1、居中,2、靠右,3、靠左
Add:新建一个word文档
Close:关闭文档,0不保存,-1保存,-2弹出框确认,注意ComThread.Release();关闭整个word进程
SaveAS:另存为
save:保存
printOut:打印
Application:得到ActiveXComponent的实例
WindowState:Application的属性,表示窗口的大小,0、default,1、maximize,2、minimize
top、left、height、width:application的属性,表示窗口的位置
ActiveXComponent.Quit:关闭所有word文档,但是不退出整个word程序
Range:表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义,进而可以得到格式的信息
Item:得到指定的表格
Rows:得到表格的所有行
Cell:表格的一个单元格
Text:word的文本内容
InsertFile:插入文件
InsertRowsBelow:在指定的行下面插入一行
InsertAfter:在指定对象后插入
Delete:删除,可以是表格的行
Count:返回数目,比如Rows、Tables的数目
Height:返回高度,比如行高、表格行的高
Split:拆分单元格,要指定行数和列数
Merge:合并单元格
Exists:指定的对象是否存在,返回bool值
Copy:复制
Paste:粘贴
Font:字体
Name:字体的名字
Bold:字体是否为粗体
Italic:字体是否为斜体
Underline:字体是否有下划线
Color:颜色
Size:大小
Borders:指定边框,-1为上边框,-2左边框,-3为下边框,-4有右边框,-5为横向边框,-6为纵向边框,-7从左上角开始的斜线,-8从左下角开始的斜线
AutoFitBehavior:自动调整大小,1为内容自动调整大小,2为窗口自动调整大小
Content:去的内容
InLineShapes:
AddPicture:增加一张图片,需要制定路径
homeKey:光标移到开头
moveDown:光标往下一行
moveUp:光标往上一行
moveRight:光标往左一列
moveLeft:光标往右一列
find:要查找的文本
Forward:向前查找
Format:查找的文本格式
MatchCase:大小写匹配
MatchWholeWord:全字匹配
Execute:开始执行查找
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* jacob 1.18: Java 1.6 and Visual Studio 2013 and Eclipse 4.3
* jacob只适合windows平台并安装office
*
* @author
*
*/
public class JacobWordHelper {
private static Logger logger = LoggerFactory
.getLogger(JacobWordHelper.class);
// word应用程序对象
private ActiveXComponent word;
// word的所有文档窗口集合
// 把每个Dispatch对象看成是对Activex控件的一个操作,这一步是获得该ActiveX控件的控制权。
private Dispatch documents;
// word中的当前文档对象
private Dispatch doc;
/**
* 光标所在 当前选定的范围或插入点 Selection对象 代表窗口或窗格中的当前所选内容。
* 所选内容代表文档中选定(或突出显示)的区域,如果文档中没有选定任何内容,则代表插入点。
* 每个文档窗格只能有一个Selection对象,并且在整个应用程序中只能有一个活动的Selection 对象。
*/
private Dispatch selection;
private boolean saveOnExit = false;
// 当前文档的所有表格
private Dispatch tables;
public ActiveXComponent getWord() {
return word;
}
public void setWord(ActiveXComponent word) {
this.word = word;
}
public Dispatch getDocuments() {
return documents;
}
public void setDocuments(Dispatch documents) {
this.documents = documents;
}
public Dispatch getDoc() {
return doc;
}
public void setDoc(Dispatch doc) {
this.doc = doc;
}
public Dispatch getSelection() {
return selection;
}
public void setSelection(Dispatch selection) {
this.selection = selection;
}
public Dispatch getTables() {
return tables;
}
public void setTables(Dispatch tables) {
this.tables = tables;
}
public boolean isSaveOnExit() {
return saveOnExit;
}
public JacobWordHelper() {
init(false);
}
public JacobWordHelper(boolean visible) {
init(visible);
}
public void init(boolean visible) {
// 初始化com线程 ComThread.InitSTA();
// 允许多个WORD进程同时运行
ComThread.InitMTA(false);
if (word == null) {
// 创建word应用程序对象
word = new ActiveXComponent("Word.Application");
// true表示word应用程序可见,false表示应用不显示,仅在后台静默处理。
word.setProperty("Visible", new Variant(visible));
// 禁用宏
word.setProperty("AutomationSecurity", new Variant(3));
}
if (documents == null) {
// 获得文档集合
documents = word.getProperty("Documents").toDispatch();
}
logger.info("init");
}
/**
* 关闭当前word文档
*/
public void closeDoc() {
if (doc != null) {
Dispatch.call(doc, "Close", new Variant(saveOnExit));
doc = null;
}
}
/**
* 退出word应用
*/
public void quit() {
closeDoc();
if (word != null) {
Dispatch.call(word, "Quit");
// wordApp.invoke("Quit", new Variant[] {});
word = null;
}
selection = null;
documents = null;
// 释放占用的内存空间,因为com的线程回收不由java的垃圾回收器处理
ComThread.Release();
logger.info("quit");
}
/**
* 打开一个已存在的文档
*
* @param docPath
*/
public void openDoc(String docPath) {
closeDoc();
// 打开word文档,获取word文档对象
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
// Dispatch doc = Dispatch.invoke( docs, "Open", Dispatch.Method, new
// Object[] { docPath, new Variant(true), new Variant(true) }, new
// int[1]).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
tables = Dispatch.get(doc, "Tables").toDispatch();
}
/**
* 保存文档
*/
public void saveDoc() {
Dispatch.call(doc, "Save");
}
/**
* 文件另存为
*
* @param savePath
* 保存路径
*/
public void saveAsDoc(String savePath) {
// Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
// "FileSaveAs", savePath);
Dispatch.call(doc, "SaveAs", new Variant(savePath));
}
public void openDocumentAndGetSelection(String docPath, String key) {
Dispatch shapes = Dispatch.get(doc, "Shapes").toDispatch(); // shape的个数
String Count = Dispatch.get(shapes, "Count").toString();
for (int i = 1; i <= Integer.parseInt(Count); i++) {
// 取得一个shape
Dispatch shape = Dispatch.call(shapes, "Item", new Variant(i))
.toDispatch();
// 从一个shape里面获取到文本框
Dispatch textframe = Dispatch.get(shape, "TextFrame").toDispatch();
boolean hasText = Dispatch.call(textframe, "HasText").getBoolean();
if (hasText) {
// 获取该文本框对象
Dispatch TextRange = Dispatch.get(textframe, "TextRange")
.toDispatch();
// 获取文本框中的字符串
String str = Dispatch.get(TextRange, "Text").toString();
// 获取指定字符key所在的文本框的位置
if (str != null && !str.equals("") && str.indexOf(key) > -1) {
// 当前文本框的位置
selection = Dispatch.get(textframe, "TextRange")
.toDispatch();
// 情况文本框内容
Dispatch.put(selection, "Text", "");
break;
}
}
}
}
/**
* 在当前插入点插入图片
*
* @param imagePath
* 图片路径
*/
public void insertImage(String imagePath) {
Dispatch.call(selection, "TypeParagraph");
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
}
/**
* 获取word文档的页码
*
* @return
*/
public int getPageSize() {
String pages = Dispatch.call(selection, "Information", new Variant(4))
.toString();
return Integer.parseInt(pages);
}
/**
* 打印当前word文档
*/
public void print() {
if (doc != null) {
Dispatch.call(doc, "PrintOut");
}
}
// public void uniteDoc(List fileList, String savepath) {
// if (fileList.size() == 0 || fileList == null) {
// return;
// }
//
// Dispatch doc1 = Dispatch.invoke(
// (Dispatch) documents, // 参数1是这个invoke方法的操作对象
// "Open", // 参数2是要对参数1执行的方法名
// Dispatch.Method, // 参数3就是参数2这个方法的具体操作
// new Object[] { (String) fileList.get(0), new Variant(false),
// new Variant(true) }, // 参数4是一系列的参数
// new int[3] // 参数5 错误参数码,常定义为new int[1]
// ).toDispatch();
// // 追加文件
// for (int i = 1; i < fileList.size(); i++) {
// Dispatch.invoke(word.getProperty("Selection").toDispatch(),// 参数1
// "insertFile", // 参数2
// Dispatch.Method, // 参数3
// new Object[] { (String) fileList.get(i), "",
// new Variant(false), new Variant(false),
// new Variant(false) },// 参数4
// new int[3]);// 参数5
// }
// // 保存新的word文件
// Dispatch.invoke(doc1, "SaveAs", Dispatch.Method, new Object[] {
// savepath, new Variant(1) }, new int[3]);
// Variant f = new Variant(false);
// Dispatch.call(doc1, "Close", f);// 该方法和get方法非常类似,他是把"Close"属性赋值给f
//
// }
/**
* 设置退出时参数
*
* @param saveOnExit
* true-退出时保存文件,false-退出时不保存文件
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 创建一个新的word文档
*/
public void createNewDoc() {
doc = Dispatch.call(documents, "Add").toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
/**
* 把选定的内容或插入点向上移动
*
* @param count
* 移动的距离
*/
public void moveUp(int count) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveUp");
}
/**
* 把选定的内容或者插入点向下移动
*
* @param count
* 移动的距离
*/
public void moveDown(int count) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveDown");
}
/**
* 把选定的内容或者插入点向左移动
*
* @param count
* 移动的距离
*/
public void moveLeft(int count) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < count; i++) {
Dispatch.call(selection, "MoveLeft");
}
}
/**
* 把选定的内容或者插入点向右移动
*
* @param count
* 移动的距离
*/
public void moveRight(int count) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveRight");
}
/**
* 把插入点移动到文件首位置
*/
public void moveStart() {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 把插入点移动到文件尾位置
*/
public void moveEnd() {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
Dispatch.call(selection, "EndKey", new Variant(6));
}
/**
* 从选定内容或插入点开始查找文本
*
* @param toFindText
* 要查找的文本
* @return true-查找到并选中该文本,false-未查找到文本
*/
public 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");
// 查找并选中
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 toFindText
* 要查找的字符串
* @param imagePath
* 图片路径
* @return
*/
public boolean replaceImage(String toFindText, String imagePath) {
if (!find(toFindText))
return false;
insertImage(imagePath);
return true;
}
/**
* 全局替换图片
*
* @param toFindText
* 要查找的字符串
* @param imagePath
* 图片路径
*/
public void replaceAllImage(String toFindText, String imagePath) {
while (find(toFindText)) {
insertImage(imagePath);
Dispatch.call(selection, "MoveRight");
}
}
/**
* 合并表格
*
* @param tableIndex
* 要合并的表格序号
* @param firstCellRowIdx
* 开始行
* @param firstCellColIdx
* 开始列
* @param secondCellRowIdx
* 结束行
* @param secondCellColIdx
* 结束列
*/
public void mergeCell(int tableIndex, int firstCellRowIdx,
int firstCellColIdx, int secondCellRowIdx, int secondCellColIdx) {
// 要合并的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
Dispatch firstCell = Dispatch.call(table, "Cell",
new Variant(firstCellRowIdx), new Variant(firstCellColIdx))
.toDispatch();
Dispatch secondCell = Dispatch.call(table, "Cell",
new Variant(secondCellRowIdx), new Variant(secondCellColIdx))
.toDispatch();
Dispatch.call(firstCell, "Merge", secondCell);
}
/**
* 给指定的单元格填写数据
*
* @param tableIndex
* 要填写的表格序号
* @param cellRowIdx
* 要填写的单元格的行坐标
* @param cellColIdx
* 要填写的单元格的列坐标
* @param txt
* 填写的内容
*/
public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
String txt) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
new Variant(cellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch.put(selection, "Text", txt);
}
/**
* 在当前文档拷贝数据到剪贴板
*
* @param toCopyText
*/
public void copy(String toCopyText) {
moveStart();
if (find(toCopyText)) {
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch.call(textRange, "Copy");
}
}
/**
* 在当前文档粘帖剪贴板数据
*
* @param pos
*/
public void paste(String pos) {
moveStart();
if (find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch.call(textRange, "Paste");
}
}
/**
* 在当前文档指定的位置拷贝表格
*
* @param pos
* 当前文档指定的位置
* @param tableIndex
* 被拷贝的表格在word文档中所处的位置
*/
public void copyTable(String pos, int tableIndex) {
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
copyTable(pos, table);
}
/**
* 在当前文档指定的位置拷贝来自另一个文档中的段落
*
* @param anotherDocPath
* 另一个文档的磁盘路径
* @param paragraphIndex
* 被拷贝的段落在另一格文档中的序号(从1开始)
* @param pos
* 当前文档指定的位置
*/
public void copyParagraphFromAnotherDoc(String anotherDocPath,
int paragraphIndex, String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();
Dispatch paragraph = Dispatch.call(paragraphs, "Item",
new Variant(paragraphIndex)).toDispatch();
Dispatch range = Dispatch.get(paragraph, "Range").toDispatch();
Dispatch.call(range, "Copy");
if (find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
}
} catch (Exception e) {
logger.error("copyParagraphFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
public void copyParagraphsFromAnotherDoc(String anotherDocPath,
String startKey, String endKey, String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();
int startIndex = searchParagraph(doc2, startKey);
logger.info("" + startIndex);
int endIndex = searchParagraph(doc2, endKey);
logger.info("" + endIndex);
if (find(pos)) {
for (int i = startIndex + 1; i < endIndex; i++) {
Dispatch paragraph = Dispatch.call(paragraphs, "Item",
new Variant(i)).toDispatch();
Dispatch range = Dispatch.get(paragraph, "Range")
.toDispatch();
Dispatch.call(range, "Copy");
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
Dispatch.call(textRange, "Select");
moveDown(1);
}
}
} catch (Exception e) {
logger.error("copyParagraphFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
public void copyParagraphsFromAnotherDoc(String anotherDocPath,
String startKey, String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();
int startIndex = searchParagraph(doc2, startKey);
logger.info("" + startIndex);
int endIndex = Dispatch.get(paragraphs, "Count").getInt();
logger.info("" + endIndex);
if (find(pos)) {
for (int i = startIndex + 1; i < endIndex; i++) {
Dispatch paragraph = Dispatch.call(paragraphs, "Item",
new Variant(i)).toDispatch();
Dispatch range = Dispatch.get(paragraph, "Range")
.toDispatch();
Dispatch.call(range, "Copy");
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
Dispatch.call(textRange, "Select");
moveDown(1);
}
}
} catch (Exception e) {
logger.error("copyParagraphFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
public int getDocEndPos(Dispatch doc) {
// 文档最后一个字的位置
selection = Dispatch.get(doc, "Selection").toDispatch();
Dispatch.call(selection, "EndKey", "6");
return Dispatch.get(selection, "End").getInt();
}
public void copyParagraphsFromAnotherDoc(String anotherDocPath,
int startIndex, int endIndex, String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();
if (find(pos)) {
for (int i = startIndex + 1; i < endIndex; i++) {
Dispatch paragraph = Dispatch.call(paragraphs, "Item",
new Variant(i)).toDispatch();
Dispatch range = Dispatch.get(paragraph, "Range")
.toDispatch();
Dispatch.call(range, "Copy");
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
Dispatch.call(textRange, "Select");
moveDown(1);
}
}
} catch (Exception e) {
logger.error("copyParagraphFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
/**
* 在当前文档末尾拷贝来自另一个文档中的段落
*
* @param anotherDocPath
* 另一个文档的磁盘路径
* @param paragraphIndex
* 被拷贝的段落在另一格文档中的序号(从1开始)
*/
public void copyParagraphFromAnotherDoc(String anotherDocPath,
int paragraphIndex) {
// 取得当前文档的内容
Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch();
// 插入特殊符定位点
Dispatch.call(wordContent, "InsertAfter", "$selection$");
copyParagraphFromAnotherDoc(anotherDocPath, paragraphIndex,
"$selection$");
}
public void logParagraphs() {
Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch();
int num = Dispatch.get(paragraphs, "Count").getInt();
for (int i = 0; i < num; i++) {
Dispatch paragraph = Dispatch.call(paragraphs, "Item",
new Variant(i + 1)).toDispatch();
Dispatch range = Dispatch.get(paragraph, "Range").toDispatch();
String ret = Dispatch.get(range, "Text").toString();
logger.info("para " + (i + 1) + ":" + ret);
}
}
public int searchParagraph(Dispatch doc, String searchKey) {
Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch();
int num = Dispatch.get(paragraphs, "Count").getInt();
logger.info("paragraphs:" + num);
for (int i = 0; i < num; i++) {
Dispatch paragraph = Dispatch.call(paragraphs, "Item",
new Variant(i + 1)).toDispatch();
Dispatch range = Dispatch.get(paragraph, "Range").toDispatch();
String para = Dispatch.get(range, "Text").toString();
if (StringUtils.contains(para, searchKey)) {
return (i + 1);
}
}
return -1;
}
/**
* 在当前文档指定的位置拷贝来自另一个文档中的表格
*
* @param anotherDocPath
* 另一个文档的磁盘路径
* @param tableIndex
* 被拷贝的表格在另一格文档中的序号(从1开始)
* @param pos
* 当前文档指定的位置
*/
public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,
String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();
Dispatch table = Dispatch.call(tables, "Item",
new Variant(tableIndex)).toDispatch();
copyTable(pos, table);
} catch (Exception e) {
logger.error("copyTableFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
public void copyTableFromAnotherDoc(String anotherDocPath, String tableKey,
String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();
Dispatch table = searchTableOne(tables, tableKey);
copyTable(pos, table);
} catch (Exception e) {
logger.error("copyTableFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
public void copyTable(String pos, Dispatch table) {
Dispatch range = Dispatch.get(table, "Range").toDispatch();
Dispatch.call(range, "Copy");
if (find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch.call(textRange, "Paste");
Dispatch.call(textRange, "Select");
moveDown(1);
enterDown(1);
}
}
public void copyTables(String pos, List<Dispatch> tbs) {
if (find(pos)) {
for (int i = 0; i < tbs.size(); i++) {
Dispatch table = tbs.get(i);
Dispatch range = Dispatch.get(table, "Range").toDispatch();
Dispatch.call(range, "Copy");
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
Dispatch.call(textRange, "Select");
moveDown(1);
enterDown(1);
}
}
}
public void copyTableAllFromAnotherDoc(String anotherDocPath,
String tableKey, String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();
List<Dispatch> tbs = searchTableAll(tables, tableKey);
copyTables(pos, tbs);
} catch (Exception e) {
logger.error("copyTableFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
/**
* 在当前文档指定的位置拷贝来自另一个文档中的图片
*
* @param anotherDocPath
* 另一个文档的磁盘路径
* @param shapeIndex
* 被拷贝的图片在另一格文档中的位置
* @param pos
* 当前文档指定的位置
*/
public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,
String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath)
.toDispatch();
Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch();
Dispatch shape = Dispatch.call(shapes, "Item",
new Variant(shapeIndex)).toDispatch();
copyTable(pos, shape);
} catch (Exception e) {
logger.error("copyImageFromAnotherDoc", e);
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(false));
doc2 = null;
}
}
}
/**
* 设置当前选定内容的字体
*
* @param bold
* 粗体
* @param italic
* 斜体
* @param underLine
* 下划线
* @param color
* 字体颜色,如"255,255,255"
* @param size
* 字体大小
* @param name
* 字体名称,例如 "宋体"
* @param scale
* 字符间距,百分比值。例如 70代表缩放为70%
* @param hidden
* 是否隐藏
*/
public void setFont(boolean bold, boolean italic, boolean underLine,
String color, int size, String name, int scale, 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", color);
Dispatch.put(font, "Size", size);
Dispatch.put(font, "Scaling", scale);
Dispatch.put(font, "Hidden", hidden);
}
/**
* 自动调整表格宽度
*/
public void autoFitTable() {
int count = Dispatch.get(tables, "Count").getInt();
for (int i = 0; i < count; i++) {
Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
.toDispatch();
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
Dispatch.call(cols, "AutoFit");
}
}
/**
* 创建表格:在指定位置新建表格,如未找到则在当前位置新建表格
*
* @param rowNum
* 行数
* @param colNum
* 列数
*/
public Dispatch createTable(String pos, int rowNum, int colNum) {
find(pos);
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch newTable = Dispatch.call(tables, "Add", range,
new Variant(rowNum), new Variant(colNum)).toDispatch();
Dispatch cols = Dispatch.get(newTable, "Columns").toDispatch();
Dispatch.call(cols, "AutoFit");
setTableBorderWidth(newTable, 25);
Dispatch.call(newTable, "Select");
moveDown(1);
enterDown(1);
return newTable;
}
/**
* 设置表格线的粗细
*
* @param table
* @param w
* w范围:0<=w<=50 1:代表最上边一条线 2:代表最左边一条线 3:最下边一条线 4:最右边一条线
* 5:除最上边最下边之外的所有横线 6:除最左边最右边之外的所有竖线 7:从左上角到右下角的斜线 8:从左下角到右上角的斜线
*/
public void setTableBorderWidth(Dispatch table, int w) {
if (w > 50 || w < 0) {
w = 25;
}
Dispatch borders = Dispatch.get(table, "Borders").toDispatch();
for (int i = 1; i < 7; i++) {
Dispatch border = Dispatch.call(borders, "Item", new Variant(i))
.toDispatch();
Dispatch.put(border, "LineWidth", new Variant(w / 100));
Dispatch.put(border, "Visible", new Variant(true));
}
}
/**
* 在指定行前面增加一行
*
* @param tableIndex
* 第N张表(从1开始)
* @param rowIndex
* 指定行的序号(从1开始)
*/
public void addTableRow(int tableIndex, int rowIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
// 指定行
Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex))
.toDispatch();
Dispatch.call(rows, "Add", new Variant(row));
}
/**
* 在第1行前增加一行
*
* @param tableIndex
* 第N张表(从1开始)
*/
public void addFirstTableRow(int tableIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
//
Dispatch row = Dispatch.get(rows, "First").toDispatch();
Dispatch.call(rows, "Add", new Variant(row));
}
/**
* 在最后1行前增加一行
*
* @param tableIndex
* 第N张表(从1开始)
*/
public void addLastTableRow(int tableIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
Dispatch row = Dispatch.get(rows, "Last").toDispatch();
Dispatch.call(rows, "Add", new Variant(row));
}
/**
* 增加一行
*
* @param tableIndex
* 第N张表(从1开始)
*/
public void addRow(int tableIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
Dispatch.call(rows, "Add");
}
/**
* 增加一列
*
* @param tableIndex
* 第N张表(从1开始)
*/
public void addCol(int tableIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有列
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
Dispatch.call(cols, "Add");
Dispatch.call(cols, "AutoFit");
}
/**
* 在指定列前面增加表格的列
*
* @param tableIndex
* 第N张表(从1开始)
* @param colIndex
* 指定列的序号(从1开始)
*/
public void addTableCol(int tableIndex, int colIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有列
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
// System.out.println(Dispatch.get(cols, "Count"));
Dispatch col = Dispatch.call(cols, "Item", new Variant(colIndex))
.toDispatch();
Dispatch.call(cols, "Add", col);
Dispatch.call(cols, "AutoFit");
}
/**
* 在第1列前增加一列
*
* @param tableIndex
*/
public void addFirstTableCol(int tableIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有列
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
Dispatch col = Dispatch.get(cols, "First").toDispatch();
Dispatch.call(cols, "Add", col);
Dispatch.call(cols, "AutoFit");
}
/**
* 在最后一列前增加一列
*
* @param tableIndex
*/
public void addLastTableCol(int tableIndex) {
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有列
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
Dispatch col = Dispatch.get(cols, "Last").toDispatch();
Dispatch.call(cols, "Add", col);
Dispatch.call(cols, "AutoFit");
}
public void addParagraph(String txt) {
Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得word文件的内容
Dispatch.call(wordContent, "InsertAfter", txt);// 插入一个段落
Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs")
.toDispatch(); // 所有段落
int paragraphCount = Dispatch.get(paragraphs, "Count").getInt(); // 一共的段落数
// 找到刚输入的段落,设置格式
Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",
new Variant(paragraphCount)).toDispatch(); // 最后一段
Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range")
.toDispatch();
Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();
Dispatch.put(font, "Name", new Variant("宋体"));
}
public String getCellString(int tableIndex, int cellRowIdx, int cellColIdx) {
return getCellString(tables, tableIndex, cellRowIdx, cellColIdx);
}
/**
* 获得指定的单元格里数据
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @return
*/
public String getCellString(Dispatch tables, int tableIndex,
int cellRowIdx, int cellColIdx) {
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
String ret = "";
try {
Dispatch cell = Dispatch.call(table, "Cell",
new Variant(cellRowIdx), new Variant(cellColIdx))
.toDispatch();
Dispatch selection = Dispatch.get(word, "Selection").toDispatch();
Dispatch.call(cell, "Select");
ret = Dispatch.get(selection, "Text").toString();
ret = ret.substring(0, ret.length() - 2).trim(); // 去掉最后的回车符
logger.info("table(idx=" + tableIndex + ",row=" + cellRowIdx
+ ",col=" + cellColIdx + "):" + ret);
} catch (Exception e) {
// logger.error("getCellString", e);
}
return ret;
}
public void logTables() {
int count = Dispatch.get(tables, "Count").getInt();
for (int i = 0; i < count; i++) {
// logger.info("table "+i+" start");
Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
.toDispatch();
// 表格的所有行
int rowNum = getRowNum(table);
int colNum = getColNum(table);
for (int j = 0; j < rowNum; j++) {
for (int k = 0; k < colNum; k++) {
getCellString(tables, i + 1, j + 1, k + 1);
}
}
// logger.info("table "+(i+1)+" end");
}
}
public int getColNum(Dispatch table) {
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
return Dispatch.get(cols, "Count").getInt();
}
public int getRowNum(Dispatch table) {
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
return Dispatch.get(rows, "Count").getInt();
}
public Dispatch searchTableOne(String tableKey) {
return searchTableOne(tables, tableKey);
}
public Dispatch searchTableOne(Dispatch tables, String tableKey) {
int count = Dispatch.get(tables, "Count").getInt();
for (int i = 0; i < count; i++) {
Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
.toDispatch();
int rowNum = getRowNum(table);
int colNum = getColNum(table);
for (int j = 0; j < rowNum; j++) {
for (int k = 0; k < colNum; k++) {
String cellStr = getCellString(tables, i + 1, j + 1, k + 1);
if (StringUtils.contains(cellStr, tableKey)) {
logger.info("searchTableOne" + (i + 1));
return table;
}
}
}
}
return null;
}
public List<Dispatch> searchTableAll(Dispatch tables, String tableKey) {
List<Dispatch> ret = new ArrayList<Dispatch>(0);
int count = Dispatch.get(tables, "Count").getInt();
out: for (int i = 0; i < count; i++) {
Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
.toDispatch();
int rowNum = getRowNum(table);
int colNum = getColNum(table);
for (int j = 0; j < rowNum; j++) {
for (int k = 0; k < colNum; k++) {
String cellStr = getCellString(tables, i + 1, j + 1, k + 1);
if (StringUtils.contains(cellStr, tableKey)) {
ret.add(table);
continue out;
}
}
}
}
return ret;
}
/**
* 设置文档所有页面的属性
*
* @param orientation
* 可取值0或1,分别代表横向和纵向
* @param leftMargin
* 左边距的值
* @param rightMargin
* 右边距的值
* @param topMargin
* 上边距的值
* @param buttomMargin
* 下边距的值
*/
public void setPageSetup(int orientation, int leftMargin, int rightMargin,
int topMargin, int buttomMargin) {
logger.info("设置页面方向和页边距...");
Dispatch pageSetup = Dispatch.get(doc, "PageSetup").toDispatch();
Dispatch.put(pageSetup, "Orientation", orientation);
Dispatch.put(pageSetup, "LeftMargin", leftMargin);
Dispatch.put(pageSetup, "RightMargin", rightMargin);
Dispatch.put(pageSetup, "TopMargin", topMargin);
Dispatch.put(pageSetup, "BottomMargin", buttomMargin);
}
/**
* 设置文档标题
*
* @param title
* 标题内容
*/
public void setTitle(String title) {
Dispatch.call(this.selection, "TypeText", title);
}
/**
* 设置对齐方式
*
* @param alignmentType
* 0-居左;1-居中;2-居右
*/
public void setAlignment(int alignmentType) {
Dispatch paragraphFormat = Dispatch.get(this.selection,
"ParagraphFormat").toDispatch();
Dispatch.put(paragraphFormat, "Alignment", alignmentType);
}
/**
* 按回车键
*
* @param count
*/
public void enterDown(int count) {
for (int i = 0; i < count; i++) {
Dispatch.call(selection, "TypeParagraph");
}
}
/**
* 保护文档
*
* @param type
* 1-wdAllowOnlyComments 仅批注 2-wdAllowOnlyFormFields 仅填写窗体
* 0-wdAllowOnlyRevisions 仅修订 -1-wdNoProtection 无保护
* 3-wdAllowOnlyReading 只读
* @param pwd
*/
public void protectedDoc(String type, String pwd) {
String protectionType = Dispatch.get(doc, "ProtectionType").toString();
if (protectionType.equals("-1")) {
Dispatch.call(doc, "Protect", Integer.parseInt(type), new Variant(
true), pwd);
}
}
/**
* 解除文档保护
*
* @param pwd
*/
public void unProtectedDoc(String pwd) {
String protectionType = Dispatch.get(doc, "ProtectionType").toString();
if (!protectionType.equals("0") && !protectionType.equals("-1")) {
Dispatch.call(doc, "Unprotect", pwd);
}
}
public String getParagraphString(int start, int end) {
logger.info("start:" + start + " end:" + end);
if (start < 0 || end < 0 || end < start)
return "";
// 标题下段落范围(该标题最后位置与下一个标题的起始位置)
Dispatch selectRange = Dispatch.call(doc, "Range", new Variant(start),
new Variant(end)).toDispatch();
return Dispatch.get(selectRange, "Text").toString();
}
public Dispatch getParagraph(int start, int end) {
logger.info("start:" + start + " end:" + end);
if (start < 0 || end < 0 || end < start)
return null;
// 标题下段落范围(该标题最后位置与下一个标题的起始位置)
return Dispatch
.call(doc, "Range", new Variant(start), new Variant(end))
.toDispatch();
}
public int getStartPos(String txt) {
moveStart();
if (find(txt)) {
return Dispatch.get(selection, "Start").getInt();
}
return -1;
}
public int getEndPos(String txt) {
moveStart();
if (find(txt)) {
return Dispatch.get(selection, "End").getInt();
}
return -1;
}
public String searchString(String begin, String end) {
int bEnd = getEndPos(begin);
int eStart = getStartPos(end);
return getParagraphString(bEnd, eStart);
}
/**
* 返回文档的保护类型
*
* @return 返回文档的保护类型
*/
public String getProtectedType() {
return Dispatch.get(doc, "ProtectionType").toString();
}
public int getTablesCount() {
return Dispatch.get(tables, "Count").getInt();
}
public void convert2Docx(String docxPath) {
// 0:Microsoft Word 97 - 2003 文档 (.doc)
// 1:Microsoft Word 97 - 2003 模板 (.dot)
// 2:文本文档 (.txt)
// 3:文本文档 (.txt)
// 4:文本文档 (.txt)
// 5:文本文档 (.txt)
// 6:RTF 格式 (.rtf)
// 7:文本文档 (.txt)
// 8:HTML 文档 (.htm)(带文件夹)
// 9:MHTML 文档 (.mht)(单文件)
// 10:MHTML 文档 (.mht)(单文件)
// 11:XML 文档 (.xml)
// 12:Microsoft Word 文档 (.docx)
// 13:Microsoft Word 启用宏的文档 (.docm)
// 14:Microsoft Word 模板 (.dotx)
// 15:Microsoft Word 启用宏的模板 (.dotm)
// 16:Microsoft Word 文档 (.docx)
// 17:PDF 文件 (.pdf)
// 18:XPS 文档 (.xps)
// 19:XML 文档 (.xml)
// 20:XML 文档 (.xml)
// 21:XML 文档 (.xml)
// 22:XML 文档 (.xml)
// 23:OpenDocument 文本 (.odt)
// 24:WTF 文件 (.wtf)
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
docxPath, new Variant(12) }, new int[1]);
}
public static void main(String[] args) {
JacobWordHelper ja = new JacobWordHelper();
try {
ja.openDoc("d://test//账.doc");
ja.convert2Docx("d://t.docx");
} catch (Exception e) {
logger.error("JacobWordHelper", e);
} finally {
ja.quit();
}
}
}