基於開源項目jacob的基礎上,封裝了操作Word常用的方法和介面。jacob項目是通過java操作com介面的工具,這部分代碼是封裝了操作word的常用com介面。需要配合jacob.dll和jacob.jar使用。
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
final class WordBean {
/**
* 讀取Com介面異常的最多重試次數.
*/
private static final int MAX_RETRY = 10;
/**
* word文檔.
*/
private Dispatch doc;
/**
* word運行程式對象.
*/
private ActiveXComponent wordApp = null;
/**
* 選定的範圍或插入點.
*/
private Dispatch selection;
/**
* 退出時是否儲存文檔.
*/
private boolean saveOnExit = true;
/**
* 建構函式.
* @param show 是否可見.
*/
public WordBean(final boolean show) {
if (wordApp == null) {
wordApp = new ActiveXComponent("Word.Application");
wordApp.setProperty("Visible", new Variant(show));
}
}
/**
* 設定退出時參數.
* @param b boolean true-退出時儲存檔案,false-退出時不儲存檔案
*/
public void setSaveOnExit(
final boolean b) {
this.saveOnExit = b;
}
/**
* 把選定的內容或插入點向上移動.
* @param pos 移動的距離
*/
public void moveUp(
final int pos) {
if (selection == null) {
selection = Dispatch.get(wordApp, "Selection").toDispatch();
}
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveUp");
}
}
/**
* 把選定的內容或者插入點向下移動.
* @param pos 移動的距離
*/
public void moveDown(
final int pos) {
if (selection == null) {
selection = Dispatch.get(wordApp, "Selection").toDispatch();
}
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveDown");
}
}
/**
* 把選定的內容或者插入點向左移動.
* @param pos 移動的距離
*/
public void moveLeft(
final int pos) {
if (selection == null) {
selection = Dispatch.get(wordApp, "Selection").toDispatch();
}
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveLeft");
}
}
/**
* 把選定的內容或者插入點向右移動.
* @param pos 移動的距離
*/
public void moveRight(
final int pos) {
if (selection == null) {
selection = Dispatch.get(wordApp, "Selection").toDispatch();
}
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveRight");
}
}
/**
* 把插入點移動到檔案首位置.
*/
public void moveStart() {
if (selection == null) {
selection = Dispatch.get(wordApp, "Selection").toDispatch();
}
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 把插入點移動到檔案尾位置.
*/
public void moveEnd() {
if (selection == null) {
selection = Dispatch.get(wordApp, "Selection").toDispatch();
}
Dispatch.call(selection, "EndKey", new Variant(6));
}
/**
* 增加縮排.
* @param pos 縮排量
*/
public void listIndent(
final 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(
final 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, "ListOutdent");
}
}
/**
* 斷行符號換行.
*/
public void enter() {
int index = 1;
while (true) {
try {
Dispatch.call(this.selection, "TypeParagraph");
break;
} catch (ComFailException e) {
if (index++ >= MAX_RETRY) {
throw e;
} else {
continue;
}
}
}
}
/**
* 插入一個換頁符.
*/
public void insertPageBreak() {
Dispatch.call(this.selection, "InsertBreak", new Variant(2));
}
/**
* 設定word文檔是否可見.
* @param isVisible 是否可見
*/
public void setIsVisible(
final boolean isVisible) {
wordApp.setProperty("Visible", new Variant(isVisible));
}
/**
* 判斷文檔是否存在.
* @param docName 文檔名稱.
* @return boolean 是否存在.
*/
private boolean isExist(
final String docName) {
boolean result = false;
File file = new File(docName);
result = file.exists();
file = null;
return result;
}
/**
* 擷取檔案名稱.
* @param docName 文檔路徑.
* @return 檔案名稱
*/
public String getFileName(
final String docName) {
int pos = docName.lastIndexOf("\\");
return docName.substring(pos + 1);
}
/**
* 開啟文檔.
* @param docName 文檔路徑.
* @throws WordException 異常
*/
public void openDocument(
final String docName)
throws WordException {
Dispatch docs = wordApp.getProperty("Documents").toDispatch();
if (isExist(docName)) {
this.closeDocument();
doc = Dispatch.call(docs, "Open", docName).toDispatch();
} else {
wordApp.invoke("Quit", new Variant[] {});
new WordException("[Open doc failed]: file["
+ docName + "] isn't existed!");
}
selection = Dispatch.get(wordApp, "Selection").toDispatch();
}
/**
* 添加一個新文檔.
* @param docName 文檔路徑.
* @throws WordException 異常
*/
public void newDocument(
final String docName)
throws WordException {
try {
Dispatch docs = wordApp.getProperty("Documents").toDispatch();
doc = Dispatch.call(docs, "Add").toDispatch();
selection = Dispatch.get(wordApp, "Selection").toDispatch();
} catch (com.jacob.com.ComFailException cfe) {
throw new WordException(cfe.getMessage());
} catch (com.jacob.com.ComException ce) {
throw new WordException(ce.getMessage());
}
}
/**
* 插入一段文字.
* @param textToInsert 文字
* @param style 樣式
*/
public void insertText(
final String textToInsert,
final String style) {
Dispatch.put(selection, "Text", textToInsert);
Dispatch.put(selection, "Style", getOutlineStyle(style));
Dispatch.call(selection, "MoveRight");
}
/**
* 插入一個圖片.
* @param imagePath 圖片路徑.
* @param style 圖片樣式
*/
public void insertImage(
final String imagePath,
final String style) {
Dispatch.call(Dispatch.get(selection, "InLineShapes")
.toDispatch(), "AddPicture", imagePath);
Dispatch.call(selection, "MoveRight");
Dispatch.put(selection, "Style", getOutlineStyle(style));
this.enter();
}
/**
* 擷取對應名稱的Style對象.
* @param style Style名稱.
* @return Style對象
*/
public Variant getOutlineStyle(
final String style) {
int index = 1;
while (true) {
try {
return Dispatch.call(
Dispatch.get(this.doc, "Styles").toDispatch(),
"Item", new Variant(style));
} catch (ComFailException e) {
if (index++ >= MAX_RETRY) {
throw e;
} else {
continue;
}
}
}
}
/**
* 插入標題.
* @param text 標題文字.
* @param style 設定標題的類型
*/
public void insertOutline(
final String text,
final String style) {
this.insertText(text, style);
this.enter();
}
/**
* 插入目錄.
* tablesOfContents的參數的含義 Add(Range As Range, [UseHeadingStyles],
* [UpperHeadingLevel], [LowerHeadingLevel], [UseFields], [TableID],
* --這兩個要不要都可以 [RightAlignPageNumbers],[IncludePageNumbers], [AddedStyles],
* --這個參數必須有值,必須是數字,如果是其它,則報com.jacob.com.ComFailException
* [UseHyperlinks],[HidePageNumbersInWeb], [UseOutlineLevels])
*/
public void insertTablesOfContents() {
Dispatch tablesOfContents = Dispatch.get(this.doc, "TablesOfContents")
.toDispatch();
Dispatch range = Dispatch.get(this.selection, "Range").toDispatch();
// Dispatch.call中的參數最多是9個,如果超過9個,請用Dispatch.callN或者Dispathc.invoke
/*
* Dispatch.invoke(tablesOfContents, "Add", Dispatch.Method,new
* Object[]{range,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]);
*/
Dispatch.callN(tablesOfContents, "Add", new Object[] {
range,
new Variant(true),
new Variant(1),
new Variant(3),
new Variant(false),
new Variant(true),
new Variant(true),
new Variant("1"),
new Variant(true),
new Variant(true)});
}
/**
* 從選定內容或插入點開始尋找文本.
* @param toFindText 要尋找的文本
* @return boolean true-尋找到並選中該文本,false-未尋找到文本
*/
public boolean find(
final 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 boolean true-尋找到並選中該文本,false-未尋找到文本
*/
public boolean replaceText(
final String toFindText,
final String newText) {
if (!find(toFindText)) {
return false;
}
Dispatch.put(selection, "Text", newText);
return true;
}
/**
* 建立表格.
* @param numCols 列數
* @param numRows 行數
* @param autoFormat 預設格式
* @return 表格對象
*/
public Dispatch createTable(
final int numRows,
final int numCols,
final int autoFormat) {
int index = 1;
while (true) {
try {
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)).toDispatch();
Dispatch.call(selection, "MoveRight");
Dispatch.call(newTable, "AutoFormat", new Variant(autoFormat));
return newTable;
} catch (ComFailException e) {
if (index++ >= MAX_RETRY) {
throw e;
} else {
continue;
}
}
}
}
/**
* 在指定的表頭裡填寫資料.
* @param table 表格
* @param cellColIdx 列號
* @param txt 文字
* @param style 樣式
*/
public void putTableHeader(
final Dispatch table,
final int cellColIdx,
final String txt,
final String style) {
Dispatch cell = Dispatch.call(table, "Cell", new Variant(1),
new Variant(cellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch.put(selection, "Text", txt);
Dispatch.put(this.selection, "Style", getOutlineStyle(style));
}
/**
* 在指定的儲存格裡填寫資料.
* @param table 表格
* @param cellRowIdx 行號
* @param cellColIdx 列號
* @param txt 文字
* @param style 樣式
*/
public void putTableCell(
final Dispatch table,
final int cellRowIdx,
final int cellColIdx,
final String txt,
final String style) {
Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
new Variant(cellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch.put(selection, "Text", txt);
Dispatch.put(this.selection, "Style", getOutlineStyle(style));
}
/**
* 關閉當前word文檔.
*/
private void closeDocument() {
if (doc != null) {
Dispatch.call(doc, "Save");
Dispatch.call(doc, "Close", new Variant(saveOnExit));
doc = null;
}
}
/**
* 檔案儲存或另存新檔.
* @param savePath 儲存或另存新檔路徑
*/
public void saveFileAs(
final String savePath) {
Dispatch.call(doc, "SaveAs", savePath);
}
/**
* 關閉文檔.
*/
public void close() {
closeDocument();
if (wordApp != null) {
Dispatch.call(wordApp, "Quit");
wordApp = null;
}
selection = null;
}
}