Java中Word怎么利用com进行操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。实例代码如下:import com.jacob.activeX.ActiveXComp
Java中Word怎么利用com进行操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
实例代码如下:
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(); } }
--结束END--
本文标题: Java中Word怎么利用com进行操作
本文链接: https://lsjlt.com/news/223170.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0