1、jacob環境部署
jdk32位或者64位把相應的.dll文件放到jdk安裝目錄的bin文件夾下
2、基礎運行
ActiveXComponent ax = new ActiveXComponent("a1");//構建ActiveX組件實例
其中的a1的值和你需要調用的ActiveX控件有關
MS控件名 |
a1的值 |
InternetExplorer |
InternetExplorer.Application |
Excel |
Excel.Application |
Word |
Word.Application |
Powerpoint |
Powerpoint.Application |
vb/java Script |
ScriptControl |
windows media Player |
WMPlayer.OCX |
Outlook |
Outlook.Application |
Visio |
Visio.Application |
DAO |
DAO.PrivateDBEngine.35 |
MultiFace |
MultiFace.Face |
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jacob.com.ComThread;
public class StudyJacob {
// word文檔
private Dispatch doc = null ;
// word運行程序對象
private ActiveXComponent word = null ;
// 所有word文檔集合
private Dispatch documents = null ;
// 選定的范圍或插入點
private static Dispatch selection = null ;
// 設置是否保存后才退出的標志
private boolean saveOnExit = true ;
/**
* word中的當前文檔
*/
private static Dispatch document = null ;
// private static Dispatch textFrame = null;
//
/**
* 所有表格
*/
private Dispatch tables;
/**
* 當前表格
*/
private Dispatch table;
/**
* 當前單元格
*/
private Dispatch cell;
/**
* 當前表格中的所有行
*/
private Dispatch rows;
/**
* 表格中的某一行
*/
private Dispatch row;
/**
* 表格中的所有列
*/
private Dispatch columns;
/**
* 表格中的某一列
*/
private Dispatch column;
/**
* 打開word時同時要打開的文檔,不指定時將新建一個空白文檔
*/
// private File openDoc;
private static Dispatch shapes;
private static Dispatch shape;
private static Dispatch textRange;
private static Dispatch textframe;
private Dispatch range;
private Dispatch paragraphs;
private Dispatch paragraph;
// constructor
public StudyJacob() {
if (word == null ) {
word = new ActiveXComponent( "Word.Application" );
word.setProperty( "Visible" , new Variant( true ));
}
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) {
if ( this .doc != null ) {
this .closeDocument();
}
doc = Dispatch.call(documents, "Open" , docPath).toDispatch();
selection = Dispatch.get(word, "Selection" ).toDispatch();
}
/**
* 關閉當前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 ;
}
/**
* 把插入點移動到文件首位置
*
*/
public void moveStart() {
if (selection == null )
selection = Dispatch.get(word, "Selection" ).toDispatch();
Dispatch.call(selection, "HomeKey" , new Variant( 6 ));
}
/**
* 在當前插入點插入字符串
*
* @param newText
*要插入的新字符串
*/
public void insertText(String newText) {
Dispatch.put(selection, "Text" , newText);
}
/**
* 在當前插入點插入圖片
*
* @param imagePath
*圖片路徑
*/
public void insertImage(String imagePath) {
Dispatch.call(Dispatch.get(selection, "InLineShapes" ).toDispatch(),
"AddPicture" , imagePath);
}
/**
* 把選定的內容或者插入點向下移動
*
* @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 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 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" );
}
/**
* 文件保存或另存為
*
* @param savePath
*一定要記得加上擴展名 .doc 保存或另存為路徑
*/
public void save(String savePath) {
Dispatch.call(
(Dispatch) Dispatch.call(word, "WordBasic" ).getDispatch(),
"FileSaveAs" , savePath);
}
/**
* 從第tIndex個Table中取出值第row行,第col列的值
*
* @param tableIndex
*文檔中的第tIndex個Table,即tIndex為索引取
* @param cellRowIdx
*cell在Table第row行
* @param cellColIdx
*cell在Talbe第col列
* @return cell單元值
* @throws Exception
*/
public String getCellString( int tableIndex, int cellRowIdx, int cellColIdx)
throws Exception {
// 所有表格
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" );
return Dispatch.get(selection, "Text" ).toString();
}
/**
* 從第tableIndex個Table中取出值第cellRowIdx行,第cellColIdx列的值
*
* @param tIndex
*文檔中的第tIndex個Table,即tIndex為索引取
* @param cellRowIdx
*cell在Table第row行
* @param cellColIdx
*cell在Talbe第col列
* @return cell單元值
* @throws Exception
*/
public void getCellValue( int tableIndex, int cellRowIdx, int cellColIdx)
throws Exception {
// 所有表格
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.call(selection, "Copy" );
}
/**
* 在當前光標處做粘貼
*/
public void paste() {
Dispatch.call(selection, "Paste" );
}
/**
* 在當前光標處添加圖片
*
* @param imgPath
*圖片的地址
*/
public void addImage(String imgPath) {
if (imgPath != "" && imgPath != null ) {
Dispatch image = Dispatch.get(selection, "InLineShapes" )
.toDispatch();
Dispatch.call(image, "AddPicture" , imgPath);
}
}
/**
* 在指定的單元格里填寫數據
*
* @param tableIndex
*文檔中的第tIndex個Table,即tIndex為索引取
* @param cellRowIdx
*cell在Table第row行
* @param cellColIdx
*cell在Talbe第col列
* @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);
}
/**
*
* 得到當前文檔的tables集合
*/
public Dispatch getTables() throws Exception {
if ( this .doc == null ) {
throw new Exception( "there is not a document can't be operate!!!" );
}
return Dispatch.get(doc, "Tables" ).toDispatch();
}
/**
*
* 得到當前文檔的表格數
*
* @param Dispatch
*/
public int getTablesCount(Dispatch tables) throws Exception {
int count = 0 ;
try {
this .getTables();
} catch (Exception e) {
throw new Exception( "there is not any table!!" );
}
count = Dispatch.get(tables, "Count" ).toInt();
return count;
}
/**
* 在當前文檔指定的位置拷貝表格
*
* @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" );
Dispatch textRange = Dispatch.get(selection, "Range" ).toDispatch();
Dispatch.call(textRange, "Paste" );
}
/**
* 在當前文檔指定的位置拷貝來自另一個文檔中的表格
*
* @param anotherDocPath
*另一個文檔的磁盤路徑
* @param tableIndex
*被拷貝的表格在另一格文檔中的位置
* @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" );
Dispatch textRange = Dispatch.get(selection, "Range" ).toDispatch();
moveDown( 1 );
Dispatch.call(textRange, "Paste" );
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc2 != null ) {
Dispatch.call(doc2, "Close" , new Variant(saveOnExit));
doc2 = null ;
}
}
}
/**
* 在當前文檔拷貝剪貼板數據
*
* @param pos
*/
public void pasteExcelSheet(String pos) {
moveStart();
Dispatch textRange = Dispatch.get(selection, "Range" ).toDispatch();
Dispatch.call(textRange, "Paste" );
}
/**
* 選中dispatch對象
*
* @param dispatch(分配,派遣)
*/
private void select(Dispatch dispatch) {
Dispatch.call(dispatch, "Select" );
}
/**
* 在當前文檔指定的位置拷貝來自另一個文檔中的圖片
*
* @param anotherDocPath
*另一個文檔的磁盤路徑
* @param shapeIndex
*被拷貝的圖片在另一格文檔中的位置
* @param pos
*當前文檔指定的位置
* @throws com.jacob.com.ComFailException
* Invoke of: Item Source: Microsoft Word 若shapeIndex不存在
*/
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" );
Dispatch textRange = Dispatch.get(selection, "Range" ).toDispatch();
moveDown( 4 );
Dispatch.call(textRange, "Paste" );
} catch (Exception e) {
e.printStackTrace();
} finally {
if (doc2 != null ) {
Dispatch.call(doc2, "Close" , new Variant(saveOnExit));
doc2 = null ;
}
}
}
/**
* 打印當前word文檔
*
* @throws Exception
* com.jacob.com.ComFailException: Invoke of: PrintOut Source:
* Microsoft Word 若無打印機
*/
public void printFile() {
if (doc != null ) {
Dispatch.call(doc, "PrintOut" );
}
}
/**
* 打印文本,反選,在文本后換行<br>
* 警告:使用了Home, End來取消選中
*
* @param s
*/
public void println(String s) {
write(s);
goToEnd();
cmd( "TypeParagraph" );
}
/**
* 執行某條宏指令
*
* @param cmd
*/
private void cmd(String cmd) {
Dispatch.call(selection, cmd);
}
/**
* 按下Ctrl + End鍵
*/
public void goToEnd() {
Dispatch.call(selection, "EndKey" , "6" );
}
/**
* 反選,再打印文本<br>
* 警告:使用了Home, End來取消選中
*/
public void print(String s) {
goToEnd();
write(s);
}
/**
* 不反選, 直接輸出文本
*
* @param s
*/
public void write(String s) {
Dispatch.put(selection, "Text" , s);
}
/**
* 反選,在文本后換行<br>
* 警告:使用了Home, End來取消選中
*/
public void println() {
home();
end();
cmd( "TypeParagraph" );
}
/**
* 按下Home鍵
*/
public void home() {
Dispatch.call(selection, "HomeKey" , "5" );
}
/**
* 按下End鍵
*/
public void end() {
Dispatch.call(selection, "EndKey" , "5" );
}
/**
* 按下Ctrl + Home鍵
*/
public void goToBegin() {
Dispatch.call(selection, "HomeKey" , "6" );
}
/**
* 設置指定表格指定列的列寬
*
* @param tableIndex
* @param columnWidth
* @param columnIndex
*/
public void setColumnWidth( int tableIndex, float columnWidth,
int columnIndex) {
this .getTable(tableIndex);
this .setColumnWidth(columnWidth, columnIndex);
}
/**
* 查找表
*
* @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;
}
public Dispatch getShapes() throws Exception {
return Dispatch.get(doc, "Shapes" ).toDispatch();
}
public int getShapesCount() throws Exception {
int count = 0 ;
count = Dispatch.get(shapes, "Count" ).toInt();
return count;
}
public Dispatch getShape( int tIndex) throws Exception {
return Dispatch.call(shapes, "Item" , new Variant(tIndex)).toDispatch();
// return Dispatch.invoke(shapes,"item",Dispatch.Method,new Object[]{
// new Integer(tIndex)},new int[1]).toDispatch();
}
public Dispatch getTextFrame() throws Exception {
return Dispatch.get(shape, "TextFrame" ).toDispatch();
}
public Dispatch getTextRange() throws Exception {
return Dispatch.get(textframe, "TextRange" ).toDispatch();
}
/**
* 設置當前表格指定列的列寬
*
* @param columnWidth
* @param columnIndex
* @throws 如果不是整齊的表格不能使用
*/
public void setColumnWidth( float columnWidth, int columnIndex) {
if (columnWidth < 11 ) {
columnWidth = 120 ;
}
if (columns == null || column == null ) {
this .getColumns();
this .getColumn(columnIndex);
}
Dispatch.put(column, "Width" , new Variant(columnWidth));
}
/**
* 設置指定表格指定列的背景色
*
* @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));
}
/**
* 初始化 com 線程
*/
public void initCom() {
ComThread.InitSTA();
}
/**
* 釋放 com 線程資源 com 的線程回收不由 java 垃圾回收機制回收
*/
public void releaseCom() {
ComThread.Release();
}
/**
* 設置當前表格指定行的背景色
*
* @param rowIndex
* @param color
*取值范圍 0 < color < 17 默認:16 淺灰色 1:黑色 2:藍色 3:淺藍 ...............
*/
public void setRowBgColor( int rowIndex, int color) {
this .getRow(rowIndex);
Dispatch shading = Dispatch.get(row, "Shading" ).toDispatch();
if (color > 16 || color < 1 )
color = 16 ;
Dispatch
.put(shading, "BackgroundPatternColorIndex" , new Variant(color));
}
/**
* 設置指定表格的指定行的背景色
*
* @param tableIndex
* @param rowIndex
* @param color
*取值范圍 0 < color < 17 默認:16 淺灰色 1:黑色 2:藍色 3:淺藍 ...............
*/
public void setRowBgColor( int tableIndex, int rowIndex, int color) {
this .getTable(tableIndex);
this .setRowBgColor(rowIndex, color);
}
/**
* 設置當前選定內容的字體
*
* @param isBold
*是否為粗體
* @param isItalic
*是否為斜體
* @param isUnderLine
*是否帶下划線
* @param color
*rgb 字體顏色 例如:紅色 255,0,0
* @param size
*字體大小 12:小四 16:三號
* @param name
*字體名稱 例如:宋體,新宋體,楷體,隸書
*/
public void setFont( boolean isBold, boolean isItalic, boolean isUnderLine,
String color, String size, String name) {
Dispatch font = Dispatch.get(selection, "Font" ).toDispatch();
Dispatch.put(font, "Name" , new Variant(name));
Dispatch.put(font, "Bold" , new Variant(isBold));
Dispatch.put(font, "Italic" , new Variant(isItalic));
Dispatch.put(font, "Underline" , new Variant(isUnderLine));
Dispatch.put(font, "Color" , color);
Dispatch.put(font, "Size" , size);
}
/**
* 恢復默認字體 不加粗,不傾斜,沒下划線,黑色,小四號字,宋體
*/
public void clearFont() {
this .setFont( false , false , false , "0,0,0" , "12" , "宋體" );
}
/**
* 對當前段落進行格式化
*
* @param align
*設置排列方式 默認:居左 0:居左 1:居中 2:居右 3:兩端對齊 4:分散對齊
* @param lineSpace
*設置行間距 默認:0 0:0 1:5 2:0 3:最小值 4:固定值
*/
public void setParaFormat( int align, int lineSpace) {
if (align < 0 || align > 4 ) {
align = 0 ;
}
if (lineSpace < 0 || lineSpace > 4 ) {
lineSpace = 0 ;
}
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat" )
.toDispatch();
Dispatch.put(alignment, "Alignment" , align);
Dispatch.put(alignment, "LineSpacingRule" , new Variant(lineSpace));
}
/**
* 還原段落默認的格式 左對齊,行間距:0
*/
public void clearParaFormat() {
this .setParaFormat( 0 , 0 );
}
/**
* 創建表格
*
* @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)).toDispatch();
Dispatch.call(selection, "MoveRight" );
}
}
/**
* 在指定行前面增加行
*
* @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" );
}
/**
* 從選定內容或插入點開始查找文本
*
* @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 ;
}
%E
/**
* 全局替換文本
*
* @param toFindText
*查找字符串
* @param newText
*要替換的內容
*/
public void replaceAllText(String toFindText, String newText) {
while (find(toFindText)) {
Dispatch.put(selection, "Text" , newText);
Dispatch.call(selection, "MoveRight" );
}
}
/**
*
* @param toFindText
*要查找的字符串
* @param imagePath
*圖片路徑
* @return 此函數將字符串替換成圖片
*/
public boolean replaceImage(String toFindText, String imagePath) {
if (!find(toFindText))
return false ;
Dispatch.call(Dispatch.get(selection, "InLineShapes" ).toDispatch(),
"AddPicture" , imagePath);
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" );
}
}
// ////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// //////////////////////////////////////////////////
/**
* 設置當前表格線的粗細 w范圍:1<w<13 超過范圍設為:w=6
*
* @param w
*/
/*
* private void setTableBorderWidth(int w) { if (w > 13 || w < 2) { w = 6; }
* Dispatch borders = Dispatch.get(table, "Borders").toDispatch(); Dispatch
* border = null;
*
* /** 設置表格線的粗細 1:代表最上邊一條線 2:代表最左邊一條線 3:最下邊一條線 4:最右邊一條線 5:除最上邊最下邊之外的所有橫線
* 6:除最左邊最右邊之外的所有豎線 7:從左上角到右下角的斜線 8:從左下角到右上角的斜線
*/
/*
* for (int i = 1; i < 7; i++) { border = Dispatch.call(borders, "Item", new
* Variant(i)) .toDispatch(); Dispatch.put(border, "LineWidth", new
* Variant(w)); Dispatch.put(border, "Visible", new Variant(true)); } }
*
*
*
* /** 復制表的最后一行到剪切板
*
* @param tableIndex
*/
/*
* public void copyLastRow(int tableIndex) {
* getRow(getRowsCount(tableIndex)); Dispatch.call(row, "select");
* Dispatch.call(selection, "Copy"); }
*
* /** 復制表的最后一行並粘貼到下一行(包括行中的數據)
*
* @param tableIndex 表的索引 @param times 粘貼的次數
*/
/*
* public void duplicateLastRow(int tableIndex, int times) {
* this.copyLastRow(tableIndex); for (int i = 0; i < times; i++) {
* Dispatch.call(selection, "Paste"); } }
*
* /** 查找當前行表格所有行中的某一行
*
* @param rowIndex @return
*/
public Dispatch getRow( int rowIndex) {
if (rows == null )
this .getRows();
row = Dispatch.invoke(rows, "item" , Dispatch.Method,
new Object[] { new Integer(rowIndex) }, new int [ 1 ])
.toDispatch();
return row;
}
public int getRowsCount() {
if (rows == null )
this .getRows();
return Dispatch.get(rows, "Count" ).getInt();
}
/**
* 得到當前表格的所有的列
*
* @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 index
*列索引
* @return
*/
public Dispatch getColumn( int columnIndex) {
if (columns == null )
this .getColumns();
return this .column = Dispatch.call(columns, "Item" ,
new Variant(columnIndex)).toDispatch();
}
/**
* 得到當前表格的列數
*
* @return
*/
public int getColumnsCount() {
this .getColumns();
return Dispatch.get(columns, "Count" ).toInt();
}
/**
* 得到指定表格的列數
*
* @param tableIndex
* @return
*/
public int getColumnsCount( int tableIndex) {
this .getTable(tableIndex);
return this .getColumnsCount();
}
/**
* 得到表的行數
*
* @param tableIndex
* @return
*/
public int getRowsCount( int tableIndex) {
this .getTable(tableIndex);
return this .getRowsCount();
}
/**
* 設置當前表格的所有行的行高
*
* @param rowHeight
*/
public void setRowHeight( float rowHeight) {
if (rowHeight > 0 ) {
if (rows == null )
this .getRows();
Dispatch.put(rows, "Height" , new Variant(rowHeight));
}
}
/**
* 設置指定表格的所有行的行高
*
* @param tableIndex
* @param rowHeight
*/
public void setRowHeight( int tableIndex, float rowHeight) {
this .getRows(tableIndex);
this .setRowHeight(rowHeight);
}
/**
* 設置當前表格指定行的行高
*
* @param rowHeight
* @param rowIndex
*/
public void setRowHeight( float rowHeight, int rowIndex) {
if (rowHeight > 0 ) {
if (rows == null || row == null ) {
this .getRows();
this .getRow(rowIndex);
}
Dispatch.put(row, "Height" , new Variant(rowHeight));
}
}
/**
* 設置指定表格的指定行的行高
*
* @param tableIndex
* @param rowHeight
* @param rowIndex
*/
public void setRowHeight( int tableIndex, float rowHeight, int rowIndex) {
this .getTable(tableIndex);
this .setRowHeight(rowHeight, rowIndex);
}
/**
* 設置當前表格的所有列的列寬
*
* @param columnWidth
*列寬 取值范圍:10<columnWidth 默認值:120
*/
public void setColumnWidth( float columnWidth) {
if (columnWidth < 11 ) {
columnWidth = 120 ;
}
if (columns == null )
this .getColumns();
Dispatch.put(columns, "Width" , new Variant(columnWidth));
}
/**
* 設置指定表格的所有列的列寬
*
* @param tableIndex
* @param columnWidth
*/
public void setColumnWidth( int tableIndex, float columnWidth) {
this .getColumns(tableIndex);
this .setColumnWidth(columnWidth);
}
/**
* 得到指定表格的多有列
*
* @param tableIndex
* @return
*/
public Dispatch getColumns( int tableIndex) {
getTable(tableIndex);
return this .getColumns();
}
/**
* 復制表的某一行
*
* @param tableIndex
* @param rowIndex
*/
public void copyRow( int tableIndex, int rowIndex) {
getTable(tableIndex);
getRows();
row = getRow(rowIndex);
Dispatch.call(row, "Select" );
Dispatch.call(selection, "Copy" );
}
/**
* 查找表的全部行
*
* @param tableIndex
* @return
*/
public Dispatch getRows( int tableIndex) {
getTable(tableIndex);
return this .getRows();
}
/**
* 查找當前表的全部行
*
* @return
*
*
*/
// 需要找到Dispatch對象,這里的Variant(1)不行一定要做成變量
public Dispatch getRows() {
Dispatch tables = Dispatch.get(doc, "Tables" ).toDispatch();
Dispatch table = Dispatch.call(tables, "Item" , new Variant( 2 ))
.toDispatch();
rows = Dispatch.get(table, "rows" ).toDispatch();
return rows;
}
/**
* 查找指定表格的單元格
*
* @param tableIndex
* @param cellRow
* @param cellColumn
* @return
*/
public Dispatch getCell( int tableIndex, int cellRow, int cellColumn) {
getTable(tableIndex);
return getCell(cellRow, cellColumn);
}
/**
* 查找當前所在表的某單元格
*
* @param cellRow
* @param cellColumn
* @return
* @throws Dispatch
* object expected
*/
public Dispatch getCell( int cellRow, int cellColumn) {
return cell = Dispatch.call(table, "Cell" , new Variant(cellRow),
new Variant(cellColumn)).toDispatch();
}
/**
* 保存文檔並退出程序
*
* @param fileName
*保存的文件名稱
* @param isSave
*是否保存修改
* @throws Exception
*/
/*
* public void saveDocAndExit(File fileName, boolean isSave) throws
* Exception { if (fileName != null) { if (!fileName.exists()) {
* fileName.createNewFile(); } Dispatch wordBasic = (Dispatch)
* Dispatch.call(word, "WordBasic").getDispatch();
* Dispatch.invoke(wordBasic, "FileSaveAs", Dispatch.Method, new Object[] {
* fileName.getPath(), new Variant(true), new Variant(false) }, new int[1]); }
*
* Dispatch.call(document, "Close", new Variant(isSave));
* Dispatch.call(word, "Quit");
*
* word = null; documents = null; document = null; selection = null; }
*/
/**
* 合並當前表格指定的單元格 如果需要一次合並幾個單元格只需要指出第一個單元格和最后一個單元格
*
* @param fstCellRowIndex
*第一個單元格的行索引
* @param fstCellColIndex
*第一個單元格的列索引
* @param secCellRowIndex
*第二個單元格的行索引
* @param secCellColIndex
*第二個單元格的列索引
*/
public void mergeCell( int fstCellRowIndex, int fstCellColIndex,
int secCellRowIndex, int secCellColIndex) {
Dispatch fstCell = Dispatch.call(table, "Cell" ,
new Variant(fstCellRowIndex), new Variant(fstCellColIndex))
.toDispatch();
Dispatch secCell = Dispatch.call(table, "Cell" ,
new Variant(secCellRowIndex), new Variant(secCellColIndex))
.toDispatch();
Dispatch.call(fstCell, "Merge" , secCell);
}
/**
* 合並當前表格指定的列
*
* @param columnIndex
*列索引
*/
public void mergeColumn( int columnIndex) {
this .getColumn(columnIndex);
Dispatch cells = Dispatch.get(column, "Cells" ).toDispatch();
Dispatch.call(cells, "Merge" );
}
/**
* 合並當前表格的指定的行
*
* @param rowIndex
*/
public void mergeRow( int rowIndex) {
this .getRow(rowIndex);
Dispatch cells = Dispatch.get(row, "Cells" ).toDispatch();
Dispatch.call(cells, "Merge" );
}
/**
* 合並指定表格的指定的行
*
* @param tableIndex
* @param rowIndex
*行索引
*/
public void mergeRow( int tableIndex, int rowIndex) {
this .getTable(tableIndex);
this .mergeRow(rowIndex);
}
/**
* 合並指定表格的指定的列
*
* @param tableIndex
* @param columnIndex
*/
public void mergeColumn( int tableIndex, int columnIndex) {
this .getTable(tableIndex);
this .mergeColumn(columnIndex);
}
/**
* 合並指定表格的指定的單元格
*
* @param tableIndex
* @param fstCellRowIndex
* @param fstCellColIndex
* @param secCellRowIndex
* @param secCellColIndex
*/
public void mergeCell( int tableIndex, int fstCellRowIndex,
int fstCellColIndex, int secCellRowIndex, int secCellColIndex) {
this .getTable(tableIndex);
this .mergeCell(fstCellRowIndex, fstCellColIndex, secCellRowIndex,
secCellColIndex);
}
public Dispatch getRangeParagraphs() throws Exception {
return Dispatch.get(range, "Paragraphs" ).toDispatch();
}
public Dispatch getParagraph( int tIndex) throws Exception {
return Dispatch.call(paragraphs, "Item" , new Variant(tIndex))
.toDispatch();
}
public Dispatch getParagraphRange() throws Exception {
return Dispatch.get(paragraph, "range" ).toDispatch();
}
public String getRangeText() throws Exception {
return Dispatch.get(range, "Text" ).toString();
}
public int getParagraphsCount() throws Exception {
int count = 0 ;
count = Dispatch.get(paragraphs, "Count" ).toInt();
return count;
}
public static void main(String[] args) {
long time1 = System.currentTimeMillis();
int i = 0 ;
ComThread.InitSTA(); // 初始化com的線程,非常重要!!使用結束后要調用 realease方法
// Instantiate objWord //Declare word object
ActiveXComponent objWord = new ActiveXComponent( "Word.Application" );
// Assign a local word object
Dispatch wordObject = (Dispatch) objWord.getObject();
// Create a Dispatch Parameter to show the document that is opened
Dispatch.put((Dispatch) wordObject, "Visible" , new Variant( true )); // new
// Variant(true)表示word應用程序可見
// Instantiate the Documents Property
Dispatch documents = objWord.getProperty( "Documents" ).toDispatch(); // documents表示word的所有文檔窗口,(word是多文檔應用程序)
// Add a new word document, Current Active Document
// Dispatch document = Dispatch.call(documents, "Add").toDispatch(); //
// 使用Add命令創建一個新文檔,用Open命令可以打開一個現有文檔
for ( int n = 0 ; n <= 10 ; n++) {
Dispatch document = Dispatch.call(documents, "Open" , "C://ABC.doc" )
.toDispatch();
Dispatch wordContent = Dispatch.get(document, "Content" )
.toDispatch(); // 取得word文件的內容
Dispatch.call(wordContent, "InsertAfter" , "這里是一個段落的內容" ); // 插入一個段落
Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs" )
.toDispatch(); // 所有段落
int paragraphCount = Dispatch.get(paragraphs, "Count" ).toInt(); // 一共的段落數
// 找到剛輸入的段落,設置格式
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, "Bold" , new Variant( true )); // 設置為黑體
Dispatch.put(font, "Italic" , new Variant( true )); // 設置為斜體
Dispatch.put(font, "Name" , new Variant( "宋體" )); //
Dispatch.put(font, "Size" , new Variant( 18 )); // 小四
Dispatch frames = Dispatch.call(wordContent, "Frames" ).toDispatch();
int frameCount = Dispatch.call(frames, "Count" ).toInt();
System.out.println( "" + frameCount + n + "/n" );
Dispatch.call(document, "SaveAs" , new Variant( "C://" + (i++)+ "abc.doc")); // 保存一個新文檔
Dispatch.call(document, "Close" , new Variant( true ));
}
//
// end for
Dispatch.call(objWord, "Quit" );
ComThread.Release(); // 釋放com線程。根據jacob的幫助文檔,com的線程回收不由java的垃圾回收器處理
long time2 = System.currentTimeMillis();
double time3 = (time2 - time1) / 0 ;
System.out.println( "/n" + time3 + " 秒." );
}
}