下面贴出对jacob进行简单封装类,暂时认为应该是网络上最全面的了,包括word打开,关闭,插入表格,替换表格,插入一个标签,插入目录等等,自己去找吧,或者自己去封装一下。
下面我贴出全部代码:
/**
* /*************************************
*
*作用:利用JACOB插件根据word模板生成报告文件!
*
*说明:传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。
* 1.word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,如:$code$、$date$……,以免执行错误的替换。
* 2.所有要替换为图片的字段,Key中需包含"image$xx"或者Value为图片的全路径(目前只判断文件后缀名为:.bmp、.jpg、.gif)。
* 3.要替换表格中的数据时,HashMap中的Key格式为"table$R@N",其中:R代表从表格的第R行开始替换,N代表word模板中的第N张表格;
* Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代表一行数据,ArrayList中第一条记录为特殊记录,
* 4.记录的是表格中要替换的列号,如:要替换第一列、第三列、第五列的数据,则第一条记录为String[3] {"1","3","5"}。
* 5.表格标签的定义形如:table$1@1、table$2@1...table$R@N,代表从第R个表格中的第N行开始填充,
* word标签的定义标签为: "soword$xx";
* @author th
*
* /*************************************
*/
public class Export2WordService {
private static Logger logger = LoggerFactory.getLogger(Export2WordService.class);
private boolean saveOnExit;
/**
* word文档
*/
private Dispatch doc = null;
/**
* word运行程序对象
*/
private ActiveXComponent word;
/**
* 所有word文档
*/
private Dispatch documents;
/**
* 选定的范围或插入点
*/
private Dispatch selection;
/**
* 表格中的所有列
*/
private Dispatch columns;
/**
* 表格中的某列
*/
private Dispatch column;
/**
* 构造函数
*/
public Export2WordService() {
try {
saveOnExit = false;
System.out.println("创建线程开始...");
ComThread.InitSTA();
System.out.println("创建线程结束!");
System.out.println("");
System.out.println("创建Word.Application开始...");
word = new ActiveXComponent("Word.Application");
System.out.println("创建Word.Application结束!");
Dispatch wordObject = word.getObject();
Dispatch.put(wordObject, "Visible", new Variant(false));
documents = word.getProperty("Documents").toDispatch();
}catch (JacobException e) {
logger.error("创建com的线程失败....");
e.printStackTrace();
}catch (Exception e) {
logger.error("创建com的线程失败....");
e.printStackTrace();
}
}
/**
* 设置参数:退出时是否保存
*
* @param saveOnExit
* true-退出时保存文件,false-退出时不保存文件
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 得到参数:退出时是否保存
*
* @return boolean true-退出时保存文件,false-退出时不保存文件
*/
public boolean getSaveOnExit() {
return saveOnExit;
}
/**
* 打开文件
* @param inputDoc 要打开的文件,全路径
* @return Dispatch 打开的文件
*/
public Dispatch open(String inputDoc) {
// return Dispatch.invoke(
// documents,
// "Open",
// Dispatch.Method,
// new Object[] {
// inputDoc, // 打开的文件路径
// new Variant(false), //是否进行转换 ConfirmConversions 否
// new Variant(false) //是否只读
// }, new int[1]).toDispatch();
return Dispatch.call(documents, "Open", inputDoc).toDispatch();
}
/**
* 打开一个保护文档,
* @param docPath-文件全名
* @param pwd-密码
*/
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();
}
/**
* 选定内容
* @return Dispatch 选定的范围或插入点
*/
public Dispatch select() {
return word.getProperty("Selection").toDispatch();
}
/**
* 把选定内容或插入点向上移动
*
* @param selection 要移动的内容
* @param count 移动的距离
*/
public void moveUp(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveUp");
}
/**
* 把选定内容或插入点向下移动
*
* @param selection 要移动的内容
* @param count 移动的距离
*/
public void moveDown(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveDown");
}
/**
* 把选定内容或插入点向左移动
*
* @param selection 要移动的内容
* @param count 移动的距离
*/
public void moveLeft(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveLeft");
}
/**
* 把选定内容或插入点向右移动
*
* @param selection 要移动的内容
* @param count 移动的距离
*/
public void moveRight(Dispatch selection, int count) {
for (int i = 0; i < count; i++)
Dispatch.call(selection, "MoveRight");
}
/**
* 把插入点移动到文件首位置
*
* @param selection 插入点
*/
public void moveStart(Dispatch selection) {
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 增加缩进
* @param pos
* 缩进量
*/
public void listIndent(int pos){
Dispatch range = Dispatch.get(this.selection,"Range").toDispatch();
Dispatch listFormat = Dispatch.get(range,"ListFormat").toDispatch();
for (int i = 0; i < pos; i++)
Dispatch.call(listFormat, "ListIndent");
}
/**
* 减少缩进
* @param pos
* 缩进量
*/
public void listOutdent(int pos){
//Selection.Range.ListFormat.ListOutdent
// Selection.Range.ListFormat.ListIndent
Dispatch range = Dispatch.get(this.selection,"Range").toDispatch();
Dispatch listFormat = Dispatch.get(range,"ListFormat").toDispatch();
for (int i = 0; i < pos; i++)
Dispatch.call(listFormat, "ListOutdent");
}
/**
* 回车换行
*/
public void enter(){
Dispatch.call(this.selection,"TypeParagraph");
}
/**
* 对当前selection设置项目符号和编号
* @param tabIndex
* 1: 项目编号
* 2:编号
* 3:多级编号
* 4:列表样式
* @param index
* 0:表示没有
*/
public void applyListTemplate(int tabIndex,int index)
{
//取得ListGalleries对象列表
Dispatch listGalleries = Dispatch.get(word, "ListGalleries").toDispatch();
//取得列表中一个对象
Dispatch listGallery = Dispatch.call(listGalleries, "Item", new Variant(tabIndex)).toDispatch();
Dispatch listTemplates = Dispatch.get(listGallery, "ListTemplates").toDispatch();
Dispatch range = Dispatch.get(this.selection, "Range").toDispatch();
Dispatch listFormat = Dispatch.get(range, "ListFormat").toDispatch();
Dispatch.call(listFormat, "ApplyListTemplate", Dispatch.call(listTemplates, "Item", new Variant(index)),new Variant(false),new Variant(0),new Variant(2));
}
/**
* 插入标题
* @param text
* @param style
* 设置标题的类型 "标题 1"
*/
public void insertOutline(String text,String style)
{
this.enter();
this.insertText(text);
// this.moveLeft(text.length());
//Dispatch.call(docStyles,"Add",new Variant("标题 1 Char"),new Variant(1));
Dispatch.put(this.selection, "Style",getOutlineStyle(style));
applyListTemplate(1,3);
this.enter();
}
public String getFileName(String docName){
int pos = docName.lastIndexOf("\\");
return docName.substring(pos+1);
}
/**
* @param olePath
*/
public Object insertOLE(String olePath) {
Object ole = Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddOLEObject", new Variant("Word.Document.8"), new Variant(olePath), new Variant(false), new Variant(true),
new Variant("C:\\WINDOWS\\Installer\\{90110804-6000-11D3-8CFE-0150048383C9}\\wordicon.exe"),
new Variant(1), new Variant(getFileName(olePath)));
Dispatch.call(selection, "MoveRight");
return ole;
}
public Object insertHyperlinks(){
Dispatch Hyperlinks = Dispatch.get(this.doc, "Hyperlinks").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
return Dispatch.call(Hyperlinks,"Add",range, new Variant("Address"),
new Variant("SubAddress"),
new Variant("table.fieldName"),//建议的数据链接处
new Variant("姓名"));
}
public com.jacob.com.Variant getOutlineStyle(String style){
//取得word中所有的类型
Dispatch docStyles = Dispatch.get(this.doc, "Styles").toDispatch();
return Dispatch.call(docStyles, "Item", new Variant(style));
}
/**
* 插入目录
*/
public void insertTablesOfContents(String pos) {
Dispatch tablesOfContents = Dispatch.get(this.doc, "TablesOfContents").toDispatch();
if (this.find(pos)) {
selection = select();
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
// Dispatch.call(textRange, "Paste");
Dispatch.callN(tablesOfContents,"Add",new Object[]{textRange,new Variant(true),new Variant(1),
new Variant(3),new Variant(true),
new Variant(true),new Variant(true)
,new Variant("1"),new Variant(true),new Variant(true)});
// Dispatch.invoke(tablesOfContents,
// "Add", Dispatch.Method,new Object[]{textRange,new Variant(true),new Variant(1),
// new Variant(3),new Variant(true),
// new Variant(true),new Variant(true)
// ,new Variant("1"),new Variant(true),new Variant(true)},new int[10]);
}
}
/**
* 从选定内容或插入点开始查找文本
*
* @param selection
* 选定内容
* @param toFindText
* 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
public boolean find(Dispatch selection, String toFindText) {
// 从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 selection
* 选定内容
* @param newText
* 替换为文本
*/
public void replace(Dispatch selection, String newText) {
// 设置替换文本
Dispatch.put(selection, "Text", newText);
}
/**
* 全局替换
*
* @param selection
* 选定内容或起始插入点
* @param oldText
* 要替换的文本
* @param newText
* 替换为文本
*/
public void replaceAll(Dispatch selection, String oldText, Object replaceObj) throws Exception{
// if(oldText.equals("table$1@38")){
// System.out.println("测试!");
// }
// 移动到文件开头
moveStart(selection);
if (oldText.startsWith("table") || replaceObj instanceof List<?>) {
replaceTable(selection, oldText, (List<?>) replaceObj);
}else if(oldText.startsWith("soword")){
System.out.println("******************执行到 " + oldText + " WORD书签 替换..........");
copyContentFromAnotherDoc(replaceObj.toString(),oldText);
}else {
String newText = (String) replaceObj;
System.out.println("******************执行到 " + oldText + " 书签 替换..........");
if (oldText.toString().toLowerCase().indexOf("image") != -1
|| oldText.toString().toLowerCase().lastIndexOf(".bmp") != -1
|| oldText.toString().toLowerCase().lastIndexOf(".jpg") != -1
|| oldText.toString().toLowerCase().lastIndexOf(".gif") != -1
|| oldText.toString().toLowerCase().lastIndexOf(".jpeg") != -1
|| oldText.toString().toLowerCase().lastIndexOf(".png") != -1)
while (find(selection, oldText)) {
if(XmlPathDef.isExistFile(newText)){
replaceImage(selection, newText);
}else{
Dispatch.put(selection, "Text", "文件不存在...");
}
Dispatch.call(selection, "MoveRight");
}else
while (find(selection, oldText)) {
replace(selection, newText);
Dispatch.call(selection, "MoveRight");
}
//System.out.println("替换值为 " + replaceObj + " 成功! \n");
}
}
/**
* 替换图片
*
* @param selection 图片的插入点
* @param imagePath 图片文件(全路径)
*/
public void replaceImage(Dispatch selection, String imagePath) throws Exception{
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
}
/**
* 替换表格
*
* @param selection 插入点
* @param tableName 表格名称,形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,
* N代表word文件中的第N张表
* @param fields 表格中要替换的字段与数据的对应表
*/
public void replaceTable(Dispatch selection, String tableName, List<?> dataList) throws Exception {
//用于测试
if(tableName.equals("table$1@28")){
//System.out.println(tableName);
}
if (dataList.size() <1) {
System.out.println("Empty table!");
return;
}
// 要填充的列
System.out.println("******************开始执行" + tableName + " 表的替换....");
// 表格序号
String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
// 从第几行开始填充
int fromRow = Integer.parseInt(tableName.substring(tableName.lastIndexOf("$") + 1, tableName.lastIndexOf("@")));
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tbIndex)).toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
// 填充表格
for (int i = 0; i < dataList.size(); i++) {
// 某一行数据
String[] datas = (String[]) dataList.get(i);
if(datas != null && datas.length > 0){
// 在表格中添加一行
if (Dispatch.get(rows, "Count").getInt() < fromRow + i){
Dispatch.call(rows, "Add");
}
// 填充该行的相关列
for (int j = 1; j <= datas.length; j++) {
// 得到单元格
/**
* 参数 table 单元格 所选中的行 该行的单元序号
*/
Dispatch cell = Dispatch.call(table, "Cell",new Variant(Integer.toString(fromRow + i)), new Variant(j)).toDispatch();
//System.out.println("******************数据库中表数据有 "+ (dataList.size()-1) + " 行,模版表格有 " + datas.length + " 列, 执行到 : 第 " + i + " 行 , 第" + j + "列!");
// 选中单元格
Dispatch.call(cell, "Select");
// 设置格式
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Bold", "0");
Dispatch.put(font, "Italic", "0");
// 输入数据
if(CommonUtils.isNotNull(datas[j-1])){
if(datas[j-1].startsWith("soword")){
//copyContentFromAnotherDoc(replaceObj.toString(),oldText);
}else if (datas[j-1].toString().toLowerCase().indexOf("image") != -1
|| datas[j-1].toString().toLowerCase().lastIndexOf(".bmp") != -1
|| datas[j-1].toString().toLowerCase().lastIndexOf(".jpg") != -1
|| datas[j-1].toString().toLowerCase().lastIndexOf(".gif") != -1
|| datas[j-1].toString().toLowerCase().lastIndexOf(".jpeg") != -1
|| datas[j-1].toString().toLowerCase().lastIndexOf(".png") != -1){
if(XmlPathDef.isExistFile(datas[j-1])){
replaceImage(selection, datas[j-1]);
}else{
Dispatch.put(selection, "Text", datas[j-1]);
}
}else{
if(datas[j-1].lastIndexOf(":") != -1 && datas[j-1].lastIndexOf(".") != -1 && XmlPathDef.isHave(datas[j-1],("/"))){
Dispatch.put(selection, "Text", "无法显示此文件...");
}else{
Dispatch.put(selection, "Text", datas[j-1]);
}
}
}else{
Dispatch.put(selection, "Text", "");
}
}
}
}
System.out.println("******************执行表的替换成功! \n");
}
/**
* 关闭文件
*
* @param document 要关闭的文件
*/
public void close(Dispatch doc) {
Dispatch.call(doc, "Close", new Variant(true));
}
/**
* 退出程序
*/
public void quit() {
word.invoke("Quit", new Variant[0]);
ComThread.Release();
}
public void moveEnd() {
if (doc == null)
doc = Dispatch.get(word, "doc").toDispatch();
}
/**
* 创建表格
*
* @param pos 位置
* @param cols 列数
* @param rows 行数
*/
public void createTable(int numCols, int numRows){//(String pos, int numCols, int numRows) {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
Dispatch range = Dispatch.get(doc, "Range").toDispatch();
Dispatch newTable = Dispatch.call(tables, "Add", range,
new Variant(numRows), new Variant(numCols)).toDispatch();
Dispatch.call(doc, "MoveRight");
moveEnd();
}
/**
* 读取文档中第paragraphsIndex段文字的内容;
* @param paragraphsIndex
* @return
*/
public String getParagraphs(int paragraphsIndex){
String ret = "";
Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch(); // 所有段落
int paragraphCount = Dispatch.get(paragraphs, "Count").getInt(); // 一共的段落数
Dispatch paragraph = null;
Dispatch range = null;
if(paragraphCount > paragraphsIndex && 0 < paragraphsIndex){
paragraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphsIndex)).toDispatch();
range = Dispatch.get(paragraph, "Range").toDispatch();
ret = Dispatch.get(range, "Text").toString();
}
return ret;
}
/**
*
* @param visible 为true表示word应用程序可见
*/
public Export2WordService(boolean visible) {
if (word == null) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(visible));
}
if (documents == null)
documents = word.getProperty("Documents").toDispatch();
}
/**
* 创建一个新的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 pos 移动的距离
*/
public void moveUp(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++)
Dispatch.call(selection, "MoveUp");
}
/**
* 把选定的内容或者插入点向下移动
*
* @param pos 移动的距离
*/
public void moveDown(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++)
Dispatch.call(selection, "MoveDown");
}
/**
* 把选定的内容或者插入点向左移动
*
* @param pos 移动的距离
*/
public void moveLeft(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveLeft");
}
}
/**
* 把选定的内容或者插入点向右移动
*
* @param pos 移动的距离
*/
public void moveRight(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++)
Dispatch.call(selection, "MoveRight");
}
/**
* 把插入点移动到文件首位置
*
*/
public void moveStart() {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 从选定内容或插入点开始查找文本
*
* @param toFindText 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
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", "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 replaceImages(String toFindText, String imagePath) {
if (!find(toFindText)){
return false;
}else{
File file = new File(imagePath);
if (file.exists()) {
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
}else{
replace(selection, "");
}
}
return true;
}
/**
* 全局替换图片
*
* @param toFindText 查找字符串
* @param imagePath 图片路径
*/
public void replaceAllImage(String toFindText, String imagePath) {
while (find(toFindText)) {
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
Dispatch.call(selection, "MoveRight");
}
}
/**
* 在当前插入点插入图片
*
* @param imagePath 图片路径
*/
public void insertImage(String imagePath) {
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
}
/**
* 合并单元格
*
* @param tableIndex
* @param fstCellRowIdx
* @param fstCellColIdx
* @param secCellRowIdx
* @param secCellColIdx
*/
public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
int secCellRowIdx, int secCellColIdx) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
Dispatch fstCell = Dispatch.call(table, "Cell",
new Variant(fstCellRowIdx), new Variant(fstCellColIdx))
.toDispatch();
Dispatch secCell = Dispatch.call(table, "Cell",
new Variant(secCellRowIdx), new Variant(secCellColIdx))
.toDispatch();
Dispatch.call(fstCell, "Merge", secCell);
}
/**
* 在指定的单元格里填写数据
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
*/
public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
String txt) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
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 pos
*/
public void copy(String toCopyText) {
moveStart();
if (this.find(toCopyText)) {
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch.call(textRange, "Copy");
}
}
/**
* 在当前文档粘帖剪贴板数据
*
* @param pos
*/
public void paste(String pos) {
moveStart();
if (this.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 tables = Dispatch.get(doc, "Tables").toDispatch();
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
Dispatch range = Dispatch.get(table, "Range").toDispatch();
Dispatch.call(range, "Copy");
if (this.find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch.call(textRange, "Paste");
}
}
/**
* 在当前文档末尾拷贝来自另一个文档中的段落
*
* @param anotherDocPath 另一个文档的磁盘路径
* @param tableIndex 被拷贝的段落在另一格文档中的序号(从1开始)
*/
public void copyParagraphFromAnotherDoc(String anotherDocPath,
int paragraphIndex) {
Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得当前文档的内容
Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入点
copyParagraphFromAnotherDoc(anotherDocPath, paragraphIndex,
"$selection$");
}
/**
* 在当前文档指定的位置拷贝来自另一个文档中的段落
*
* @param anotherDocPath 另一个文档的磁盘路径
* @param tableIndex 被拷贝的段落在另一格文档中的序号(从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 (this.find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(saveOnExit));
doc2 = null;
}
}
}
/**
* 在当前文档指定的位置拷贝来自另一个文档中的表格
*
* @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();
Dispatch range = Dispatch.get(table, "Range").toDispatch();
Dispatch.call(range, "Copy");
if (this.find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(saveOnExit));
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();
Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();
Dispatch.call(imageRange, "Copy");
if (this.find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range")
.toDispatch();
Dispatch.call(textRange, "Paste");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(saveOnExit));
doc2 = null;
}
}
}
/**
* 在当前文档末尾拷贝另一个文档的所有内容
*/
public void copyContentFromAnotherDoc(String anotherDocPath) {
try {
Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得当前文档的内容
Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入点
copyContentFromAnotherDoc(anotherDocPath, "$selection$");
this.moveEnd();
this.moveUp(1);
//Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入点
Dispatch.put(selection, "Text", "$selection$");
copyContentFromAnotherDoc(anotherDocPath, "$selection$");
//Dispatch.call(wordContent, "Delete").toDispatch();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 拷贝另个文档的所有内容
* @param pos 当前文档指定的位置
*/
public void copyContentFromAnotherDoc(String anotherDocPath, String pos) {
Dispatch doc2 = null;
try {
doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();
if(doc2 != null && !doc2.equals("")){
Dispatch content = Dispatch.get(doc2, "Content").toDispatch();
Dispatch.call(content, "Copy");
if (this.find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch.call(textRange, "Paste");
}
}else{
replace(selection, "");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc2 != null) {
Dispatch.call(doc2, "Close", new Variant(saveOnExit));
doc2 = null;
}
}
}
/**
* 创建表格
*
* @param pos 位置
* @param cols 列数
* @param rows 行数
*/
public void createTable(String pos, int numCols, int numRows) {
if (find(pos)) {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch newTable = Dispatch.call(tables, "Add", range,new Variant(numRows), new Variant(numCols),new Variant(1)).toDispatch();
Dispatch.call(selection, "MoveRight");
}
}
/**
* 获取某个表格的所有行
*
* @param tableIndex word文件中的第N张表(从1开始)
*/
public Variant getTableAllRowNum(int tableIndex) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
System.out.println("表格的总行数为:" + Dispatch.get(rows, "Count"));
return Dispatch.get(rows, "Count");
}
/**
* 获取某个表格的所有行
*
* @param tableIndex word文档中的第N张表(从1开始)
*/
public Variant getTableAllColNum(int tableIndex) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有列
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
System.out.println(Dispatch.get(cols, "Count"));
return Dispatch.get(cols, "Count");
}
/**
* 在指定行前面增加行
*
* @param tableIndex word文件中的第N张表(从1开始)
* @param rowIndex 指定行的序号(从1开始)
*/
public void addTableRow(int tableIndex, int rowIndex) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
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 word文档中的第N张表(从1开始)
*/
public void addFirstTableRow(int tableIndex) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
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 word文档中的第N张表(从1开始)
*/
public void addLastTableRow(int tableIndex) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
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 word文档中的第N张表(从1开始)
*/
public void addRow(int tableIndex) {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有行
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
Dispatch.call(rows, "Add");
}
/**
* 增加一列(在最后面添加一列)
*
* @param tableIndex word文档中的第N张表(从1开始)
*/
public void addCol(int tableIndex) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
.toDispatch();
// 表格的所有行
Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
Dispatch.call(cols, "Add").toDispatch();
Dispatch.call(cols, "AutoFit");
}
/**
* 在指定列前面增加表格的列
*
* @param tableIndex word文档中的第N张表(从1开始)
* @param colIndex 指定列的序号 (从1开始)
*/
public void addTableCol(int tableIndex, int colIndex) {
// 所有表格
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
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 col = Dispatch.get(cols, "First").toDispatch();
Dispatch.call(cols, "Add", col).toDispatch();
Dispatch.call(cols, "AutoFit");
}
/**
* 在第1列前增加一列
*
* @param tableIndex word文档中的第N张表(从1开始)
*/
public void addFirstTableCol(int tableIndex) {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
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).toDispatch();
Dispatch.call(cols, "AutoFit");
}
/**
* 在最后一列前增加一列
*
* @param tableIndex word文档中的第N张表(从1开始)
*/
public void addLastTableCol(int tableIndex) {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
// 要填充的表格
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).toDispatch();
Dispatch.call(cols, "AutoFit");
}
/**
* 自动调整表格
*/
public void autoFitTable() {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
int count = Dispatch.get(tables, "Count").toInt();
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");
}
}
/**
* 调用word里的宏以调整表格的宽度,其中宏保存在document下
*
*/
@SuppressWarnings("deprecation")
public void callWordMacro() {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
int count = Dispatch.get(tables, "Count").toInt();
Variant vMacroName = new Variant("Normal.NewMacros.tableFit");
@SuppressWarnings("unused")
Variant vParam = new Variant("param1");
Variant para[] = new Variant[] { vMacroName };
for (int i = 0; i < para.length; i++) {
Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
.toDispatch();
Dispatch.call(table, "Select");
Dispatch.call(word, "Run", "tableFitContent");
}
}
/**
* 设置当前选定内容的字体
*
* @param boldSize
* @param italicSize
* @param underLineSize 下划线
* @param colorSize 字体颜色
* @param size 字体大小
* @param name 字体名称
*/
public void setFont(boolean bold, boolean italic, boolean underLine,
String colorSize, String size, String name) {
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);
}
/**
* 设置指定表格指定列的背景色
*
* @param tableIndex
* @param columnIndex
* @param color 取值范围 0 < color < 17 默认:16 浅灰色 1:黑色 2:蓝色 3:浅蓝 ...............
*/
public void setColumnBgColor( int tableIndex, int columnIndex, int color) {
this.getTable(tableIndex);
this.setColumnBgColor(columnIndex, color);
}
/**
* 设置当前表格指定列的背景色
*
* @param columnIndex
* @param color 取值范围 0 < color < 17 默认:16 浅灰色 1:黑色 2:蓝色 3:浅蓝 ...............
*/
public void setColumnBgColor( int columnIndex, int color) {
this.getColumn(columnIndex);
Dispatch shading = Dispatch.get(column, "Shading" ).toDispatch();
if (color > 16 || color < 1 )
color = 16 ;
Dispatch.put(shading, "BackgroundPatternColorIndex" , new Variant(color));
}
/**
* 得到当前表格的某一列
*
* @param index
* 列索引
* @return
*/
public Dispatch getColumn( int columnIndex) {
if (columns == null )
this.getColumns();
return this.column = Dispatch.call(columns, "Item" ,
new Variant(columnIndex)).toDispatch();
}
/**
* 得到指定表格的多有列
*
* @param tableIndex
* @return
*/
public Dispatch getColumns( int tableIndex) {
getTable(tableIndex);
return this.getColumns();
}
/**
* 得到当前表格的所有的列
*
* @return
*/
// 需要找到Dispatch对象,这里的Variant(1)不行一定要做成变量
public Dispatch getColumns() {
// this.getTables();
Dispatch tables = Dispatch.get(doc, "Tables" ).toDispatch();
Dispatch table = Dispatch.call(tables, "Item" , new Variant( 1 ))
.toDispatch();
return this .columns = Dispatch.get(table, "Columns" ).toDispatch();
}
/**
* 查找表
*
* @param tableIndex
* @return
*/
public Dispatch getTable( int tableIndex) {
Dispatch tables = Dispatch.get(doc, "Tables" ).toDispatch();
Dispatch table = Dispatch.call(tables, "Item" , new Variant(tableIndex))
.toDispatch();
return table;
}
/**
* 保护当前档,如果不存在, 使用expression.Protect(Type, NoReset, Password)
*
* @param pwd
* WdProtectionType 可以是下列 WdProtectionType 常量之一:
* 1-wdAllowOnlyComments, 2-wdAllowOnlyFormFields, 0-wdAllowOnlyRevisions,
* -1-wdNoProtection, 3-wdAllowOnlyReading
*
* 使用参照 main1()
*/
public void protectedWord(String pwd){
String protectionType = Dispatch.get(doc, "ProtectionType").toString();
if(protectionType.equals("-1")){
Dispatch.call(doc, "Protect", new Variant(3), new Variant(true), pwd);
}
}
/**
* 解除文档保护,如果存在
* @param pwd
* WdProtectionType 常量之一(Long 类型,只读):
* 1-wdAllowOnlyComments,2-wdAllowOnlyFormFields、
* 0-wdAllowOnlyRevisions,-1-wdNoProtection, 3-wdAllowOnlyReading
*
* 使用参照 main1()
*/
public void unProtectedWord(String pwd){
String protectionType = Dispatch.get(doc, "ProtectionType").toString();
if(protectionType.equals("3")){
Dispatch.call(doc, "Unprotect", pwd);
}
}
/**
* 设置word文档安全级别
* @param value
* 1-msoAutomationSecurityByUI 使用“安全”对话框指定的安全设置。
* 2-msoAutomationSecurityForceDisable 在程序打开的所有文件中禁用所有宏,而不显示任何安全提醒。
* 3-msoAutomationSecurityLow 启用所有宏,这是启动应用程序时的默认值。
*/
public void setAutomationSecurity(int value){
word.setProperty("AutomationSecurity", new Variant(value));
}
/**
* 设置页眉文字
* @param cont
* @return
*
* Sub AddHeaderText()
* '设置页眉或页脚中的文字
* '由 Headers、Footers 和 HeaderFooter 属性返回 HeaderFooter 对象。下列示例更改当前页眉中的文字。
* With ActiveDocument.ActiveWindow.View
* .SeekView = wdSeekCurrentPageHeader
* Selection.HeaderFooter.Range.Text = "Header text"
* .SeekView = wdSeekMainDocument
* End With
* End Sub
*/
public void setHeaderContent(String cont){
Dispatch activeWindow = Dispatch.get(doc, "ActiveWindow").toDispatch();
Dispatch view = Dispatch.get(activeWindow, "View").toDispatch();
//Dispatch seekView = Dispatch.get(view, "SeekView").toDispatch();
Dispatch.put(view, "SeekView", new Variant(9)); //wdSeekCurrentPageHeader-9
Dispatch headerFooter = Dispatch.get(selection, "HeaderFooter").toDispatch();
Dispatch range = Dispatch.get(headerFooter, "Range").toDispatch();
Dispatch.put(range, "Text", new Variant(cont));
//String content = Dispatch.get(range, "Text").toString();
Dispatch font = Dispatch.get(range, "Font").toDispatch();
Dispatch.put(font, "Name", new Variant("楷体_GB2312"));
Dispatch.put(font, "Bold", new Variant(true));
//Dispatch.put(font, "Italic", new Variant(true));
//Dispatch.put(font, "Underline", new Variant(true));
Dispatch.put(font, "Size", 9);
Dispatch.put(view, "SeekView", new Variant(0)); //wdSeekMainDocument-0恢复视图;
}
/***************************************************************************
* 删除书签
*
* @param mark 书签名
* @param info 可替换
* @return
*/
public boolean deleteBookMark(String markKey, String info) throws Exception{
Dispatch activeDocument = word.getProperty("ActiveDocument").toDispatch();
Dispatch bookMarks = word.call(activeDocument, "Bookmarks").toDispatch();
boolean isExists = word.call(bookMarks, "Exists", markKey).toBoolean();
if (isExists) {
Dispatch n = Dispatch.call(bookMarks, "Item", markKey).toDispatch();
Dispatch.call(n, "Delete");
return true;
}
return false;
}
/***************************************************************************
* 根据书签插入数据
*
* @param bookMarkKey 书签名
* @param info 插入的数据
* @return
*/
public boolean intoValueBookMark(String bookMarkKey, String info) throws Exception{
Dispatch activeDocument = word.getProperty("ActiveDocument").toDispatch();
Dispatch bookMarks = word.call(activeDocument, "Bookmarks").toDispatch();
boolean bookMarkExist = word.call(bookMarks, "Exists", bookMarkKey).toBoolean();
if (bookMarkExist) {
Dispatch rangeItem = Dispatch.call(bookMarks, "Item", bookMarkKey).toDispatch();
Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
Dispatch.put(range, "Text", new Variant(info));
return true;
}
return false;
}
/**
* 文件保存或另存为
*
* @param savePath 保存或另存为路径
*/
public void save(String savePath) {
Dispatch.call(
(Dispatch) Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);
}
/**
* 关闭当前word文档
*
*/
public void closeDocument() {
if (doc != null) {
Dispatch.call(doc, "Save");
Dispatch.call(doc, "Close", new Variant(saveOnExit));
doc = null;
}
}
/**
* 关闭全部应用
*
*/
public void close() {
closeDocument();
if (word != null) {
Dispatch.call(word, "Quit");
word = null;
}
selection = null;
documents = null;
}
/**
* 打印当前word文档
*
*/
public void printFile() {
if (doc != null) {
Dispatch.call(doc, "PrintOut");
}
}
有了这个工具类之后 就是自己去调用它的方法了,很全我说了,需要认真去阅读,找其中的方法就ok了!
(未完待续)