用jacob实现导出带图片的word文档package net.jite.pmp.oa.service;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import net.jite.pmp.oa.vo.OATempData;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* desc:
*
*
* @version CVS $Revision: 1.6 $ $Date: 2009/05/15 09:26:27 $
*/
public class OAHelper {
/**
* word运行程序对象
*/
private ActiveXComponent word;
/**
* 所有word文档
*/
private Dispatch documents;
/**
* word文档
*/
private Dispatch doc;
/**
* 选定的内容或插入点
*/
private Dispatch selection;
/**
* 退出时保存
*/
private boolean saveOnExit = true;
public OAHelper () {
if (word == null) {
word = new ActiveXComponent(\"Word.Application\");
word.setProperty(\"Visible\
}
if (documents == null)
documents = word.getProperty(\"Documents\").toDispatch();
}
/**
* 设置参数:退出时是否保存
*
* @param saveOnExit
* true-退出时保存文件,false-退出时不保存文件
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 得到参数:退出时是否保存
*
* @return boolean true-退出时保存文件,false-退出时不保存文件
*/
public boolean getSaveOnExit() {
return saveOnExit;
}
//
/////////////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////*****以下为文件及程序操作
*****/////////////////////////////
/**
* 创建新文件
*/
public void createDoc() {
doc = Dispatch.call(documents, \"Add\").toDispatch();
selection = Dispatch.get(word, \"Selection\").toDispatch();
}
/**
* 打开文件
*
* @param inputPath
* 要打开的文件路径
*/
public void openDoc(String inputPath) {
doc = Dispatch.call(documents, \"Open\
selection = Dispatch.get(word, \"Selection\").toDispatch();
}
/**
* 打开文件
*
* @param input
* 要打开的文件路径
*/
public void openDoc(InputStream input) {
doc = Dispatch.call(documents, \"Open\
selection = Dispatch.get(word, \"Selection\").toDispatch();
}
/**
* 保存文件
*
* @param outputPath
* 输出文件路径
*/
public void saveDoc(String outputPath) {
Dispatch.call(Dispatch.call(word, \"WordBasic\").getDispatch(),
\"FileSaveAs\
}
/**
* 保存文件
*
* @param outputPath
* 输出文件路径
*/
public void saveDoc(OutputStream output) {
Dispatch.call(Dispatch.call(word, \"WordBasic\").getDispatch(),
\"FileSaveAs\
}
/**
* 关闭文件
*
* @param doc
* 要关闭的文件
*/
public void closeDoc(Dispatch doc) {
Dispatch.call(doc, \"Close\
}
/**
* 退出程序
*/
public void quit() {
word.invoke(\"Quit\
ComThread.Release();
}
// ///////////////////////////////*****以上为文件及程序操作*****////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////////////////
// //////////////////////////////*****以下为查找及移动操作*****////////////////////////////////
/**
* 把选定内容或插入点向上移动
*
* @param selection
* 插入点
* @param count
* 移动的距离
*/
public void moveUp(Dispatch selection, int count) {
if (selection == null)
selection = Dispatch.get(word, \"Selection\").toDispatch();
for (int i = 0; i < count; i++)
Dispatch.call(selection, \"MoveUp\");
}
/**
* 把选定内容或插入点向下移动
*
* @param selection
* 插入点
* @param count
* 移动的距离
*/
public void moveDown(Dispatch selection, int count) {
if (selection == null)
selection = Dispatch.get(word, \"Selection\").toDispatch();
for (int i = 0; i < count; i++)
Dispatch.call(selection, \"MoveDown\");
}
/**
* 把选定内容或插入点向左移动
*
* @param selection
* 插入点
* @param count
* 移动的距离
*/
public void moveLeft(Dispatch selection, int count) {
if (selection == null)
selection = Dispatch.get(word, \"Selection\").toDispatch();
for (int i = 0; i < count; i++)
Dispatch.call(selection, \"MoveLeft\");
}
/**
* 把选定内容或插入点向右移动
*
* @param selection
* 插入点
* @param count
* 移动的距离
*/
public void moveRight(Dispatch selection, int count) {
if (selection == null)
selection = Dispatch.get(word, \"Selection\").toDispatch();
for (int i = 0; i < count; i++)
Dispatch.call(selection, \"MoveRight\");
}
/**
* 把插入点移动到文件首位置
*
* @param selection
* 插入点
*/
public void move2Home(Dispatch selection) {
if (selection == null)
selection = Dispatch.get(word, \"Selection\").toDispatch();
Dispatch.call(selection, \"HomeKey\
}
/**
* 从选定内容或插入点开始查找文本
*
* @param textToFind
* 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
public boolean findText(String textToFind) {
if (textToFind == null || textToFind.equals(\"\"))
return false;
Dispatch find = Dispatch.call(selection, \"Find\").toDispatch();// 从selection所在位置开始查询
Dispatch.put(find, \"Text\设置要查找的内容
Dispatch.put(find, \"Forward\向前查找
Dispatch.put(find, \"Format\设置格式
Dispatch.put(find, \"MatchCase\大小写匹配
Dispatch.put(find, \"MatchWholeWord\全字匹配
return Dispatch.call(find, \"Execute\").getBoolean();// 查找并选中
}
// //////////////////////////////*****以上为查找及移动操作*****////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////////////////
// ///////////////////////////*****以下为表格基本操作*****/////////////////////////////////////
/**
* 在当前位置创建表格
*
* @param cols
* 列数
* @param rows
* 行数
*/
public void createTable(int numCols, int numRows) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();
Dispatch range = Dispatch.get(selection, \"Range\").toDispatch();
Dispatch.call(tables, \"Add\
new Variant(numCols)).toDispatch();
Dispatch.call(selection, \"MoveRight\");
}
/**
* 在指定行前面增加行
*
* @param tableIndexword
* 表格序号(从1开始)
* @param rowIndex
* 指定行号(从1开始)
*/
public void addRow(int tableIndex, int rowIndex) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch rows = Dispatch.get(table, \"Rows\").toDispatch();// 表格的所有行
Dispatch row = Dispatch.call(rows, \"Item\
.toDispatch();// 获取指定行
Dispatch.call(rows, \"Add\增加行
}
/**
* 在第1行前增加一行
*
* @param tableIndexword
* 表格序号(从1开始)
*/
public void addRowBeforeFirst(int tableIndex) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch rows = Dispatch.get(table, \"Rows\").toDispatch();// 表格的所有行
Dispatch row = Dispatch.get(rows, \"First\").toDispatch();// 获取首行
Dispatch.call(rows, \"Add\增加行
}
/**
* 在最后1行前增加一行
*
* @param tableIndex
* 表格序号(从1开始)
*/
public void addRowAfterLast(int tableIndex) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch rows = Dispatch.get(table, \"Rows\").toDispatch();// 表格的所有行
Dispatch row = Dispatch.get(rows, \"Last\").toDispatch();// 获取最后一行
Dispatch.call(rows, \"Add\增加行
}
/**
* 在指定列前面增加表格的列
*
* @param tableIndex
* 表格序号(从1开始)
* @param colIndex
* 指定列号(从1开始)
*/
public void addCol(int tableIndex, int colIndex) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch cols = Dispatch.get(table, \"Columns\").toDispatch();// 表格的所有列
Dispatch col = Dispatch.call(cols, \"Item\
.toDispatch();// 获取指定列
Dispatch.call(cols, \"Add\增加列
Dispatch.call(cols, \"AutoFit\");
}
/**
* 在第1列前增加一列
*
* @param tableIndex
* 表格序号(从1开始)
*/
public void addColBeforeFirst(int tableIndex) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch cols = Dispatch.get(table, \"Columns\").toDispatch();// 表格的所有列
Dispatch col = Dispatch.get(cols, \"First\").toDispatch();// 获取首列
Dispatch.call(cols, \"Add\增加列
Dispatch.call(cols, \"AutoFit\");
}
/**
* 在最后一列前增加一列
*
* @param tableIndex
* 表格序号(从1开始)
*/
public void addColAfterLast(int tableIndex) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch cols = Dispatch.get(table, \"Columns\").toDispatch();// 表格的所有列
Dispatch col = Dispatch.get(cols, \"Last\").toDispatch();// 获取最后一列
Dispatch.call(cols, \"Add\增加列
Dispatch.call(cols, \"AutoFit\");
}
/**
* 合并单元格
*
* @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\
.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\合并单元格
}
/**
* 在指定的单元格里填写数据
*
* @param tableIndex
* 表格序号
* @param cellRowIdx
* 单元格行号
* @param cellColIdx
* 单元格列号
* @param newText
* 要填入的数据
*/
public void putTextToCell(int tableIndex, int cellRowIdx, int cellColIdx,
String newText) {
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch cell = Dispatch.call(table, \"Cell\
new Variant(cellColIdx)).toDispatch();// 获取单元格
Dispatch.call(cell, \"Select\");// 选中单元格
Dispatch.put(selection, \"Text\填入数据
}
// ///////////////////////////*****以上为表格基本操作*****//////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////////////////
// ///////////////////////*****以下为文本、图片及表格的插入替换操作*****//////////////////////////
/**
* 在当前插入点插入字符串
*
* @param newText
* 要插入的字符串
*/
public void insertText(String newText) {
Dispatch.put(selection, \"Text\
}
/**
* 在当前插入点插入图片
*
* @param imagePath
* 图片文件路径
*/
public void insertImage(String imagePath) {
Dispatch.call(Dispatch.get(selection, \"InLineShapes\").toDispatch(),
\"AddPicture\
}
/**
* 替换为文本
*
* @param textToFind
* 要查找的文本
* @param newText
* 要替换的新内容
* @return boolean true-替换成功,false-未找到文本
*/
public boolean replaceText(String textToFind, String newText) {
if (!findText(textToFind))
return false;
Dispatch.put(selection, \"Text\
return true;
}
/**
* 用文本替换所有文本
*
* @param textToFind
* 要查找的文本
* @param newText
* 要替换的新内容
*/
public void replaceAllText(String textToFind, String newText) {
while (findText(textToFind)) {
Dispatch.put(selection, \"Text\
Dispatch.call(selection, \"MoveRight\");
}
}
/**
* 替换为图片
*
* @param textToFind
* 要查找的文本
* @param imagePath
* 图片文件路径
*/
public boolean replaceWithImage(String textToFind, String imagePath) {
if (!findText(textToFind))
return false;
Dispatch.call(Dispatch.get(selection, \"InLineShapes\").toDispatch(),
\"AddPicture\
return true;
}
/**
* 用图片替换所有文本
*
* @param textToFind
* 要查找的文本
* @param imagePath
* 图片文件路径
*/
public void replaceAllWithImage(String textToFind, String imagePath) {
while (findText(textToFind)) {
Dispatch.call(Dispatch.get(selection, \"InLineShapes\").toDispatch(),
\"AddPicture\
Dispatch.call(selection, \"MoveRight\");
}
}
/**
* 填充表格
*
* @param tableName
* 表格名称,形如table$R@N,R代表从表格中的第R行开始填充,N代表word文件中的第N张表
* @param dataList
* 表格中要填充的数据列表,index=0为列信息,index>0为行数据
*/
public void replaceWithTable(String tableName, List dataList) {
if (dataList.size() <= 1) {
System.out.println(\"Empty table!\");
return;
}
Dispatch tables = Dispatch.get(doc, \"Tables\").toDispatch();// 所有表格
String tbIndex = tableName.substring(tableName.lastIndexOf(\"@\") + 1);// 表
格序号
Dispatch table = Dispatch.call(tables, \"Item\
.toDispatch();// 要填充的表格
Dispatch rows = Dispatch.get(table, \"Rows\").toDispatch();// 表格的所有行
String[] cols = (String[]) dataList.get(0);// 需要填充的列
int fromRow = Integer.parseInt(tableName.substring(tableName
.lastIndexOf(\"$\") + 1, tableName.lastIndexOf(\"@\")));// 从第几行开始填充
// 填充表格
for (int i = 1; i < dataList.size(); i++) {
String[] datas = (String[]) dataList.get(i);// 某一行数据
// 在表格中添加一行
if (Dispatch.get(rows, \"Count\").getInt() < fromRow + i - 1)
Dispatch.call(rows, \"Add\");
// 填充该行的相关列
for (int j = 0; j < datas.length; j++) {
Dispatch cell = Dispatch.call(table, \"Cell\
Integer.toString(fromRow + i - 1), cols[j])
.toDispatch();// 得到单元格
Dispatch.call(cell, \"Select\");// 选中单元格
Dispatch font = Dispatch.get(selection, \"Font\").toDispatch();// 设置格式
Dispatch.put(font, \"Bold\
Dispatch.put(font, \"Italic\
Dispatch.put(selection, \"Text\j]);// 填入数据
}
}
}
/**
* 全部替换
*
* @param textToFind
* 要查找的文本
* @param replaceObj
* 替换为对象(包含文本、图片、表格)
*/
public void replaceAll(String textToFind, Object replaceObj) {
move2Home(selection);// 移动到文件开头
if (textToFind.startsWith(\"table\") || replaceObj instanceof List) {
replaceWithTable(textToFind, (List) replaceObj);
} else {
String newText = (String) replaceObj;
if (textToFind.indexOf(\"image\") != -1
|| newText.lastIndexOf(\".bmp\") != -1
|| newText.lastIndexOf(\".jpg\") != -1
|| newText.lastIndexOf(\".gif\") != -1)
replaceAllWithImage(textToFind, newText);
else
replaceAllText(textToFind, newText);
}
}
/**
* 根据模板、数据生成word文件
*
* @param inputPath
* 模板文件路径
* @param outputPath
* 输出文件路径
* @param data
* 数据包,为HashMap对象,对象中的Key代表word模板中要查找替换的字段,Value代表用替 * 换的值
*
* 模板中所有要替换的字段(Key)以特殊字符开头和结尾,如:$code$、$date$
* 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径(后缀名 *为:.bmp、.jpg、.gif)
* 要替换表格中的数据时,Key格式为\"table$R@N\",其中R代表从表格的第R行开始替换,N代表word模板*中的第N张表格
* Value为ArrayList对象,所含的对象统一为String[],每一个String[]代表一行数据,且长度必须相同
* 其中第一条记录为特殊记录,记录表格中要替换的列号
* 如:要替换第一列、第三列、第五列的数据,则第一条记录为String[3]{\"1\
* @throws Exception
*/
public void toWord(String inputPath, String outputPath, HashMap data) throws Exception {
String oldText;
Object newValue;
try {
openDoc(inputPath);
Iterator keys = data.keySet().iterator();
while (keys.hasNext()) {
oldText = (String) keys.next();
newValue = data.get(oldText);
replaceAll(oldText, newValue);
}
saveDoc(outputPath);
} catch (Exception e) {
System.out.println(\"toword[Java2Word]------------操作word文件失败!\"
+ e.getMessage());
throw e;
} finally {
if (doc != null)
closeDoc(doc);
}
}
// /////////////////////*****以上为文本、图片及表格的插入替换操作*****/////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////////////////
public void setDocContentAndSave(String templatePath, String outPath, OATempData p) {
try {
openDoc(templatePath);
replaceAll(\"${title}\
replaceAll(\"${project_name}\
replaceAll(\"${p_coutns}\
replaceAll(\"${all_budget}\
replaceAll(\"${p_year}\
saveDoc(outPath);
createDoc();
} finally {
quit();
}
}
public void setDocContentAndSave(String input, String output, String title) {
try {
openDoc(input);
replaceAll(\"${title}\
saveDoc(output);
createDoc();
} finally {
quit();
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容