【JAVA】jacob写word
生活随笔
收集整理的這篇文章主要介紹了
【JAVA】jacob写word
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package cn.zssoft.business.pxgl.struts.action.test;
import java.io.File;import cn.zssoft.tools.WordTools;public class JacobTest2 {public static void createANewFileTest() {WordBean wordBean = new WordBean();// word.openWord(true);// 打開 word 程序wordBean.setVisible(true);wordBean.createNewDocument();// 創建一個新文檔wordBean.setLocation();// 設置打開后窗口的位置wordBean.insertText("你好");// 向文檔中插入字符wordBean.insertJpeg("D:" + File.separator + "a.jpg"); // 插入圖片// 如果 ,想保存文件,下面三句// word.saveFileAs("d://a.doc");// word.closeDocument();// word.closeWord();}public static void openAnExistsFileTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前臺打開word 程序,或者后臺運行wordBean.openFile("d://a.doc");wordBean.insertJpeg("D:" + File.separator + "a.jpg"); // 插入圖片(注意剛打開的word// ,光標處于開頭,故,圖片在最前方插入)wordBean.save();wordBean.closeDocument();wordBean.closeWord();}public static void insertFormatStr(String str) {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前臺打開word 程序,或者后臺運行wordBean.createNewDocument();// 創建一個新文檔wordBean.insertFormatStr2(str,"",12);// 插入一個段落,對其中的字體進行了設置}public static void insertTableTest() {WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前臺打開word 程序,或者后臺運行wordBean.createNewDocument();// 創建一個新文檔wordBean.setLocation();wordBean.insertTable("表名", 3, 2);wordBean.saveFileAs("d://sss.doc");wordBean.closeDocument();wordBean.closeWord();}public static void mergeTableCellTest() { WordBean wordBean = new WordBean();wordBean.setVisible(true); // 是否前臺打開word 程序,或者后臺運行wordBean.openFile("d://sss.doc");wordBean.mergeCellTest();}public static void main(String[] args) {// 進行測試前要保證d://a.jpg 圖片文件存在// createANewFileTest();//創建一個新文件// openAnExistsFileTest();// 打開一個存在 的文件//insertFormatStr("格式 化字符串");//對字符串進行一定的修飾//insertTableTest();// 創建一個表格// mergeTableCellTest();// 對表格中的單元格進行合并my();}public static void my() {
// WordBean wordBean = new WordBean();WordTools wordBean = new WordTools();wordBean.setVisible(true); // 是否前臺打開word 程序,或者后臺運行wordBean.createNewDocument();// 創建一個新文檔wordBean.myInsert("aaaa",12);// 插入一個段落,對其中的字體進行了設置wordBean.myInsert("bbbb",12);// 插入一個段落,對其中的字體進行了設置wordBean.myInsert("cccc",12);// 插入一個段落,對其中的字體進行了設置wordBean.setYmYj();wordBean.saveFileAs("d://sss.doc");wordBean.closeDocument();wordBean.closeWord();}
}
package cn.zssoft.business.pxgl.struts.action.test;import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;class WordBean {// 代表一個word 程序private ActiveXComponent MsWordApp = null;// 代表進行處理的word 文檔private Dispatch document = null;public WordBean() {// Open Word if we/'ve not done it alreadyif (MsWordApp == null) {MsWordApp = new ActiveXComponent("Word.Application");}}// 設置是否在前臺打開 word 程序 ,public void setVisible(boolean visible) {MsWordApp.setProperty("Visible", new Variant(visible));// 這一句作用相同// Dispatch.put(MsWordApp, "Visible", new Variant(visible));}// 創建一個新文檔public void createNewDocument() {// Find the Documents collection object maintained by Word// documents表示word的所有文檔窗口,(word是多文檔應用程序)Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();// Call the Add method of the Documents collection to create// a new document to editdocument = Dispatch.call(documents, "Add").toDispatch();}// 打開一個存在的word文檔,并用document 引用 引用它public void openFile(String wordFilePath) {// Find the Documents collection object maintained by Word// documents表示word的所有文檔窗口,(word是多文檔應用程序)Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();document = Dispatch.call(documents, "Open", wordFilePath,new Variant(true)/* 是否進行轉換ConfirmConversions */,new Variant(false)/* 是否只讀 */).toDispatch();// document = Dispatch.invoke(documents, "Open", Dispatch.Method,// new Object[] { wordFilePath, new Variant(true),// new Variant(false)// }, new int[1]).toDispatch();}// 向 document 中插入文本內容public void insertText(String textToInsert) {// Get the current selection within Word at the moment.// a new document has just been created then this will be at// the top of the new doc 獲得選 中的內容,如果是一個新創建的文件,因里面無內容,則光標應處于文件開頭處Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();// 取消選中,應該就是移動光標 ,否則 新添加的內容會覆蓋選中的內容Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));// Put the specified text at the insertion pointDispatch.put(selection, "Text", textToInsert);// 取消選中,應該就是移動光標Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));}// 向文檔中添加 一個圖片,public void insertJpeg(String jpegFilePath) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();Dispatch.call(image, "AddPicture", jpegFilePath);}// 段落的處理,插入格式化的文本public void insertFormatStr(String text) {Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的內容Dispatch.call(wordContent, "InsertAfter", text);// 插入一個段落到最后// Dispatch.call(wordContent, "InsertState", text);// 插入一個段落到最后Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落int paragraphCount = Dispatch.get(paragraphs, "Count").changeType(Variant.VariantInt).getInt();// 一共的段落數// 找到剛輸入的段落,設置格式Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是剛插入的)// Range 對象表示文檔中的一個連續范圍,由一個起始字符位置和一個終止字符位置定義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(12)); // 小四Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch.call(selection, "TypeParagraph");// 插入一個空行Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式Dispatch.put(alignment, "Alignment", "3"); // (1:置中 2:靠右 3:靠左)}// 段落的處理,插入格式化的文本/*** text 文本* fontZt 字體* fontSize 字大小*/public void insertFormatStr2(String text,String fontZt, int fontSize) {Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的內容Dispatch.call(wordContent, "InsertAfter", text);// 插入一個段落到最后Dispatch.call(wordContent, "InsertState", text);// 插入一個段落到最后Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落int paragraphCount = Dispatch.get(paragraphs, "Count").changeType(Variant.VariantInt).getInt();// 一共的段落數// 找到剛輸入的段落,設置格式Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是剛插入的)// Range 對象表示文檔中的一個連續范圍,由一個起始字符位置和一個終止字符位置定義Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range").toDispatch();Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();Dispatch.put(font, fontZt, new Variant(true)); // 設置為黑體Bold//Dispatch.put(font, "Italic", new Variant(true)); // 設置為斜體Dispatch.put(font, "Name", new Variant("宋體")); //Dispatch.put(font, "Size", new Variant(fontSize)); // 小四Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();Dispatch.call(selection, "TypeParagraph");// 插入一個空行Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式Dispatch.put(alignment, "Alignment", "3"); // (1:置中 2:靠右 3:靠左)}public void myInsert(String str){Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 輸入內容需要的對象Dispatch.call(selection, "TypeText", str); // 寫入標題內容 // 標題格行Dispatch.call(selection, "TypeParagraph"); // 空一行段落} //設置頁眉頁腳public void setYmYj(){Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); /****插入頁眉頁腳*****///取得活動窗體對象 Dispatch ActiveWindow = MsWordApp.getProperty( "ActiveWindow").toDispatch(); //取得活動窗格對象 Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch(); //取得視窗對象 Dispatch View = Dispatch.get(ActivePane, "View").toDispatch(); /****設置頁眉*****/Dispatch.put(View, "SeekView", "10");Dispatch.put(selection, "Text", "1");//頁眉顯示文字/****設置頁腳,動態插入頁碼*****/Dispatch.put(View, "SeekView", "10");final Dispatch Sections = Dispatch.get(document, "Sections").toDispatch(); final Dispatch item = Dispatch.call(Sections, "Item", new Variant(1)).toDispatch(); final Dispatch footer = Dispatch.get(item, "Footers").toDispatch(); final Dispatch f1 = Dispatch.call(footer, "Item", new Variant(1)).toDispatch(); final Dispatch range = Dispatch.get(f1, "Range").toDispatch(); final Dispatch fields = Dispatch.get(range, "Fields").toDispatch();Dispatch paragraphFormat=(Dispatch) Dispatch.get(selection,"ParagraphFormat").getDispatch(); Dispatch.put(paragraphFormat, "Alignment", 1);Dispatch.call(fields, "Add", Dispatch.get(selection, "Range").toDispatch(), new Variant(-1), "Page", true).toDispatch();Dispatch.call(selection, "TypeText", "/");Dispatch.call(fields, "Add", Dispatch.get(selection, "Range").toDispatch(), new Variant(-1), "NumPages",true).toDispatch();Dispatch font = Dispatch.get(range, "Font").toDispatch();Dispatch.put(font,"Name",new Variant("宋體_GB2312"));//Dispatch.put(font, "Bold", new Variant(true));Dispatch.put(font, "Size", 9);}// word 中在對表格進行遍歷的時候 ,是先列后行 先column 后cell// 另外下標從1開始public void insertTable(String tableTitle, int row, int column) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 輸入內容需要的對象Dispatch.call(selection, "TypeText", tableTitle); // 寫入標題內容 // 標題格行Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "MoveDown"); // 游標往下一行// 建立表格Dispatch tables = Dispatch.get(document, "Tables").toDispatch();// int count = Dispatch.get(tables,// "Count").changeType(Variant.VariantInt).getInt(); // document中的表格數量// Dispatch table = Dispatch.call(tables, "Item", new Variant(// 1)).toDispatch();//文檔中第一個表格Dispatch range = Dispatch.get(selection, "Range").toDispatch();// /當前光標位置或者選中的區域Dispatch newTable = Dispatch.call(tables, "Add", range,new Variant(row), new Variant(column), new Variant(1)).toDispatch(); // 設置row,column,表格外框寬度Dispatch cols = Dispatch.get(newTable, "Columns").toDispatch(); // 此表的所有列,int colCount = Dispatch.get(cols, "Count").changeType(Variant.VariantInt).getInt();// 一共有多少列 實際上這個數==columnSystem.out.println(colCount + "列");for (int i = 1; i <= colCount; i++) { // 循環取出每一列Dispatch col = Dispatch.call(cols, "Item", new Variant(i)).toDispatch();Dispatch cells = Dispatch.get(col, "Cells").toDispatch();// 當前列中單元格int cellCount = Dispatch.get(cells, "Count").changeType(Variant.VariantInt).getInt();// 當前列中單元格數 實際上這個數等于rowfor (int j = 1; j <= cellCount; j++) {// 每一列中的單元格數// Dispatch cell = Dispatch.call(cells, "Item", new// Variant(j)).toDispatch(); //當前單元格// Dispatch cell = Dispatch.call(newTable, "Cell", new// Variant(j) , new Variant(i) ).toDispatch(); //取單元格的另一種方法// Dispatch.call(cell, "Select");//選中當前單元格// Dispatch.put(selection, "Text",// "第"+j+"行,第"+i+"列");//往選中的區域中填值,也就是往當前單元格填值putTxtToCell(newTable, j, i, "第" + j + "行,第" + i + "列");// 與上面四句的作用相同}}}/** *//*** 在指定的單元格里填寫數據** @param tableIndex* @param cellRowIdx* @param cellColIdx* @param txt*/public void putTxtToCell(Dispatch table, int cellRowIdx, int cellColIdx,String txt) {Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),new Variant(cellColIdx)).toDispatch();Dispatch.call(cell, "Select");Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 輸入內容需要的對象Dispatch.put(selection, "Text", txt);}/** *//*** 在指定的單元格里填寫數據** @param tableIndex* @param cellRowIdx* @param cellColIdx* @param txt*/public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,String txt) {// 所有表格Dispatch tables = Dispatch.get(document, "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 selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 輸入內容需要的對象Dispatch.put(selection, "Text", txt);}// 合并兩個單元格public void mergeCell(Dispatch cell1, Dispatch cell2) {Dispatch.call(cell1, "Merge", cell2);}public void mergeCell(Dispatch table, int row1, int col1, int row2, int col2) {Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(row1),new Variant(col1)).toDispatch();Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(row2),new Variant(col2)).toDispatch();mergeCell(cell1, cell2);}public void mergeCellTest() {Dispatch tables = Dispatch.get(document, "Tables").toDispatch();int tableCount = Dispatch.get(tables, "Count").changeType(Variant.VariantInt).getInt(); // document中的表格數量Dispatch table = Dispatch.call(tables, "Item", new Variant(tableCount)).toDispatch();// 文檔中最后一個tablemergeCell(table, 1, 1, 1, 2);// 將table 中x=1,y=1 與x=1,y=2的兩個單元格合并}// ========================================================/** *//*** 把選定的內容或光標插入點向上移動** @param pos* 移動的距離*/public void moveUp(int pos) {Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 輸入內容需要的對象for (int i = 0; i < pos; i++) {// MoveDown MoveLeft moveRight// moveStart ( Dispatch.call(selection, "HomeKey", new Variant(6));// )// moveEnd Dispatch.call(selection, "EndKey", new Variant(6));Dispatch.call(selection, "MoveUp");}}/** *//*** 從選定內容或插入點開始查找文本** @param toFindText* 要查找的文本* @return boolean true-查找到并選中該文本,false-未查找到文本*/public boolean find(String toFindText) {if (toFindText == null || toFindText.equals(""))return false;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 輸入內容需要的對象// 從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*/public boolean replaceText(String toFindText, String newText) {if (!find(toFindText))return false;Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 輸入內容需要的對象Dispatch.put(selection, "Text", newText);return true;}public void printFile() {// Just print the current document to the default printerDispatch.call(document, "PrintOut");}// 保存文檔的更改public void save() {Dispatch.call(document, "Save");}public void saveFileAs(String filename) {Dispatch.call(document, "SaveAs", filename);}public void closeDocument() {// Close the document without saving changes// 0 = wdDoNotSaveChanges// -1 = wdSaveChanges// -2 = wdPromptToSaveChangesDispatch.call(document, "Close", new Variant(0));document = null;}public void closeWord() {Dispatch.call(MsWordApp, "Quit");MsWordApp = null;document = null;}// 設置wordApp打開后窗口的位置public void setLocation() {Dispatch activeWindow = Dispatch.get(MsWordApp, "Application").toDispatch();Dispatch.put(activeWindow, "WindowState", new Variant(1)); // 0=default// 1=maximize// 2=minimizeDispatch.put(activeWindow, "Top", new Variant(300));Dispatch.put(activeWindow, "Left", new Variant(300));Dispatch.put(activeWindow, "Height", new Variant(600));Dispatch.put(activeWindow, "width", new Variant(800));}
}
總結
以上是生活随笔為你收集整理的【JAVA】jacob写word的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手绘线条一直画不直_板绘线条不流畅怎么办
- 下一篇: 【JSP】测试Ajax