实例代码如下:
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordBean {
// word文档
private Dispatch doc;
// word运行程序对象
private ActiveXComponent word;
// 所有word文档集合
private Dispatch documents;
// 选定的范围或插入点
private Dispatch selection;
private boolean saveonExit = true;
public WordBean()throws Exception{
if (word == null) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false)); //不可见打开word
word.setProperty("AutomationSecurity", new Variant(3)); //禁用宏
}
if (documents == null)
documents = word.getProperty("documents").toDispatch();
}
public void setSaveonExit(boolean saveOnExit) {
this.saveonExit = saveOnExit;
}
public void createNewdocument() {
doc = Dispatch.call(documents, "Add").toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
public void opendocument(String docPath) {
closedocument();
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
public void opendocumentonlyRead(String docPath, String pwd)throws Exception {
closedocument();
// doc = Dispatch.invoke(documents, "Open", Dispatch.Method,
//new Object[]{docPath, new Variant(false), new Variant(true), new Variant(true), pwd},
//new int[1]).toDispatch();//打开word文件
doc = Dispatch.callN(documents, "Open", new Object[]{docPath, new Variant(false),
new Variant(true), new Variant(true), pwd, "", new Variant(false)}).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
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();
}
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");
}
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");
}
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");
}
}
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));
}
@SuppressWarnings("static-access")
public boolean find(String toFindText) {
if (toFindText == null || toFindText.equals(""))
return false;
// 从selection所在位置开始查询
Dispatch find = word.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", toFindText);
// 向前查找
Dispatch.put(find, "Forward", "True");
// 设置格式
Dispatch.put(find, "Format", "True");
// 大小写匹配
Dispatch.put(find, "MatchCase", "True");
// 全字匹配
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
return Dispatch.call(find, "Execute").getBoolean();
}
public boolean replaceText(String toFindText, String newText) {
if (!find(toFindText))
return false;
Dispatch.put(selection, "Text", newText);
return true;
}
public void replaceAllText(String toFindText, String newText) {
while (find(toFindText)) {
Dispatch.put(selection, "Text", newText);
Dispatch.call(selection, "MoveRight");
}
}
public void insertText(String newText) {
Dispatch.put(selection, "Text", newText);
}
public boolean replaceImage(String toFindText, String imagePath) {
if (!find(toFindText))
return false;
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
return true;
}
public void replaceAllImage(String toFindText, String imagePath) {
while (find(toFindText)) {
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
Dispatch.call(selection, "MoveRight");
}
}
public void insertImage(String imagePath) {
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);
}
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);
}
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);
}
public String getTxtFromCell(int tableIndex, int cellRowIdx, int cellColIdx) {
// 所有表格
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");
String ret = "";
ret = Dispatch.get(selection, "Text").toString();
ret = ret.substring(0, ret.length()-1); //去掉最后的回车符;
return ret;
}
public void pasteExcelSheet(String pos) {
moveStart();
if (this.find(pos)) {
Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
Dispatch.call(textRange, "Paste");
}
}
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");
}
}
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;
}
}
}
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 createTable(String pos, int numCols, int numRows) {
if (find(pos)) {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
@SuppressWarnings("unused")
Dispatch newTable = Dispatch.call(tables, "Add", range,
new Variant(numRows), new Variant(numCols)).toDispatch();
Dispatch.call(selection, "MoveRight");
} else {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
@SuppressWarnings("unused")
Dispatch newTable = Dispatch.call(tables, "Add", range,
new Variant(numRows), new Variant(numCols)).toDispatch();
Dispatch.call(selection, "MoveRight");
}
}
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));
}
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));
}
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));
}
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");
}
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");
}
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");
}
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");
}
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");
}
@SuppressWarnings("deprecation")
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");
}
}
@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");
@SuppressWarnings("unused")
Variant para[] = new Variant[] { vMacroname };
for (int i = 0; i < count; i++) {
Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
.toDispatch();
Dispatch.call(table, "Select");
Dispatch.call(word, "Run", "tableFitContent");
}
}
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);
}
public void setTableCellSelected(int tableIndex, int cellRowIdx, int cellColIdx){
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");
}
public void setCellVerticalAlign(int verticalAlign){
Dispatch cells = Dispatch.get(selection, "Cells").toDispatch();
Dispatch.put(cells, "VerticalAlignment", new Variant(verticalAlign));
}
@SuppressWarnings("deprecation")
public void setApplyTableFormat(){
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
int tabCount = Integer.valueOf(Dispatch.get(tables, "Count").toString()); //System.out.println(tabCount);
System.out.println("*******************************************************");
for(int i=1; i<=tabCount; i++){
Dispatch table = Dispatch.call(tables, "Item", new Variant(i)).toDispatch();
Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
if(i==1){
Dispatch.put(rows, "Alignment", new Variant(2)); //1-居中,2-Right
continue ;
}
Dispatch.put(rows, "Alignment", new Variant(1)); //1-居中
Dispatch.call(table, "AutoFitBehavior", new Variant(1));//设置自动调整表格方式,1-根据窗口自动调整
Dispatch.put(table, "PreferredWidthType", new Variant(1));
Dispatch.put(table, "PreferredWidth", new Variant(700));
System.out.println(Dispatch.get(rows, "HeightRule").toString());
Dispatch.put(rows, "HeightRule", new Variant(1)); //0-自动wdRowHeightAuto,1-最小值wdRowHeightAtLeast, 2-固定wdRowHeightExactly
Dispatch.put(rows, "Height", new Variant(0.04*28.35));
//int oldAlign = Integer.valueOf(Dispatch.get(rows, "Alignment").toString());
//System.out.println("Algin:" + oldAlign);
}
}
public void setParagraphsProperties(int alignment, int lineSpaceingRule,
int lineUnitBefore, int lineUnitAfter, int characterUnitFirstLineIndent){
Dispatch paragraphs = Dispatch.get(selection, "Paragraphs").toDispatch();
Dispatch.put(paragraphs, "Alignment", new Variant(alignment));//对齐方式
Dispatch.put(paragraphs, "LineSpacingRule", new Variant(lineSpaceingRule)); //行距
Dispatch.put(paragraphs, "LineUnitBefore", new Variant(lineUnitBefore)); //段前
Dispatch.put(paragraphs, "LineUnitAfter", new Variant(lineUnitAfter)); //段后
Dispatch.put(paragraphs, "CharacterUnitFirstLineIndent",
new Variant(characterUnitFirstLineIndent)); //首行缩进字符数
}
public void getParagraphsProperties(){
Dispatch paragraphs = Dispatch.get(selection, "Paragraphs").toDispatch();
String val = Dispatch.get(paragraphs, "LineSpacingRule").toString(); //行距
val = Dispatch.get(paragraphs, "Alignment").toString(); //对齐方式
val = Dispatch.get(paragraphs, "LineUnitBefore").toString(); //段前行数
val = Dispatch.get(paragraphs, "LineUnitAfter").toString(); //段后行数
val = Dispatch.get(paragraphs, "FirstLineIndent").toString(); //首行缩进
val = Dispatch.get(paragraphs, "CharacterUnitFirstLineIndent").toString(); //首行缩进字符数
}
public void save(String savePath) {
Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
"FileSaveAs", savePath);
}
public void saveAsHtml(String htmlPath){
Dispatch.invoke(doc,"SaveAs", Dispatch.Method,
new Object[]{htmlPath, new Variant(8)}, new int[1]);
}
public void closedocument(int val) {
Dispatch.call(doc, "Close", new Variant(val));
doc = null;
}
public void closedocument() {
if (doc != null) {
Dispatch.call(doc, "Save");
Dispatch.call(doc, "Close", new Variant(saveOnExit));
doc = null;
}
}
public void closedocumentWithoutSave(){
if (doc != null) {
Dispatch.call(doc, "Close", new Variant(false));
doc = null;
}
}
public void close() {
//closedocument();
if (word != null) {
Dispatch.call(word, "Quit");
word = null;
}
selection = null;
documents = null;
}
public void printFile() {
if (doc != null) {
Dispatch.call(doc, "PrintOut");
}
}
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);
}
}
public void unProtectedWord(String pwd){
String protectionType = Dispatch.get(doc, "ProtectionType").toString();
if(protectionType.equals("3")){
Dispatch.call(doc, "Unprotect", pwd);
}
}
public void setAutomationSecurity(int value){
word.setProperty("AutomationSecurity", new Variant(value));
}
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;
}
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恢复视图;
}
public static void main(String[] args)throws Exception{
WordBean word = new WordBean();
word.opendocument("D:/竞价平台.doc");
word.setHeaderContent("*****************88设置页眉内容11111111111111111!");
//word.unProtectedWord("1qaz");
//word.protectedWord("123");
System.out.print(word.getParagraphs(3));
word.closedocument();
word.close();
}
}
//更新目录并自动保存办法
ActiveXComponent app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("documents").toDispatch();
Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[] { "D:/aaa/a.doc", new Variant(false),
new Variant(false) }, new int[1]).toDispatch();
Dispatch activedocument = app.getProperty("Activedocument").toDispatch();
Dispatch tablesOfContents = Dispatch.get(activedocument,"TablesOfContents").toDispatch();
Variant tablesOfContent = Dispatch.call(tablesOfContents, "Item", new Variant(1));
Dispatch toc = tablesOfContent.toDispatch();
toc.call(toc, "Update");
Dispatch.call(doc, "Save");
Dispatch.call(doc, "Close", new Variant(-1));
app.invoke("Quit", new Variant[] {});
总结:
本文关于Java编程实现调用com操作Word方法的介绍就到这里,希望对大家有所帮助。如果有什么问题可以留言,小编会及时回复大家的。



