jacob 操作Word

最近使用java去操作word,在这记录一下wordBean


废话不多说,直接上代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class WordBean {
	
    // 代表一个word 程序  
    private ActiveXComponent MsWordApp = null; 
    
    // 代表进行处理的word 文档  
    private Dispatch document = null; 
    
    public WordBean() {  
        // Open Word if we/'ve not done it already  
        if (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 setOrientation(boolean 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 edit  
        document = 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[).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 point  
        Dispatch.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 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", "2"); // (1:置中 2:靠右 3:靠左)  
    }  
    
    // word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell  
    // 另外下标从1开始  
    public void insertTable(Map<String, Object> result, int row, int column,String[][] dataArr) {  
    	
        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
        Dispatch alignment = Dispatch.get(selection,  "ParagraphFormat" ).toDispatch();
        Dispatch.put(alignment,  "Alignment" , "1");
        Dispatch.call(selection, "TypeText", result.get("title")); // 写入标题内容 // 标题格行 
        Dispatch.call(selection, "TypeParagraph"); // 空一行段落
        Dispatch.call(selection, "TypeText", result.get("checkPollouts")); // 写入企业与排口 
        Dispatch.put(alignment,  "Alignment" , "0");
        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.put(alignment,  "Alignment" , "0");//居左对齐
        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 rows = Dispatch.get(newTable,  "rows" ).toDispatch();
        int rowHeight = 25;
        Dispatch.put(rows,  "Height" ,  new  Variant(rowHeight));
        Dispatch cols = Dispatch.get(newTable, "Columns").toDispatch(); // 此表的所有列,
        //Dispatch.put(cols, "Alignment", new Variant(2)); // 1-居中,2-Right
        int colCount = Dispatch.get(cols, "Count").changeType(  
                Variant.VariantInt).getInt();// 一共有多少列 实际上这个数==column  
        System.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();// 当前列中单元格
            Dispatch.put(cells, "VerticalAlignment", new Variant(1));// 对齐方式为垂直对齐( 0-顶端, 1-居中, 3-底端 ) 
            //Dispatch.put(cells,  "HorizontalAlignment" , new Variant(1));//对齐方式为水平对齐( 0-顶端, 1-居中, 3-底端 ) 
            int cellCount = Dispatch.get(cells, "Count").changeType(  
                    Variant.VariantInt).getInt();// 当前列中单元格数 实际上这个数等于row  
            for (int j = 1; j <= cellCount; j++) {// 每一列中的单元格数
            	if(j>=cellCount-1){
            		if(i==4 && j== cellCount){
            			Dispatch cell = Dispatch.call(newTable, "Cell", new Variant(j), new Variant(i)).toDispatch();  
                    	Dispatch.call(cell, "Select");
            			Dispatch.call(selection, "MoveLeft"); 
	            		Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();  
		                Dispatch picture = Dispatch.call(image, "AddPicture", dataArr[j-1][i-1]).toDispatch(); // 添加图片 
		                Dispatch.call(picture, "Select"); // 选中图片
		                Dispatch.put(picture, "Width", new Variant(120)); // 图片的宽度
		                Dispatch.put(picture, "Height", new Variant(90)); // 图片的高度
            		}else{
            			Dispatch.put(alignment,  "Alignment" , "1");//居中对齐
            			putTxtToCell(newTable, j, i, dataArr[j-1][i-1]);
            		}
            	}else{
            		if(i==3 && j>2){
                    	Dispatch.put(alignment,  "Alignment" , "0");//居左对齐 
                    }else{
                    	Dispatch.put(alignment,  "Alignment" , "1");//居中对齐
                    }
                    putTxtToCell(newTable, j, i, dataArr[j-1][i-1]);// 与上面四句的作用相同  
            	}
            }
            
        }

        Dispatch.call(selection, "MoveDown"); // 游标往下一行 
    } 
    
    // word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell  
    // 另外下标从1开始  
    public void editTable(int row, int column) {  
    	
    	// 所有表格  
        Dispatch tables = Dispatch.get(document, "Tables").toDispatch();  
        // 要填充的表格  
        Dispatch table = Dispatch.call(tables, "Item", new Variant(1)).toDispatch();
        for (int i = 1; i <= row; i++) { // 循环取出每一行    
        	for (int j = 1; j <= column; j++) {// 每一列
        		int columnWidth = 0; 
        		if(i<row-1){
        			// 四列
    				columnWidth = 30;
    				if(j==3){
        				columnWidth = 300;
        			}else if(j==4){
        				columnWidth = 60;
        			}
        		}
        		else{
        			if(j%2==1){
        				columnWidth = 80;
        			}else{
        				columnWidth = 130;
        			}
        			
        		}
        		Dispatch cells = Dispatch.call(table, "Cell", new Variant(i), new Variant(j)).toDispatch();
            	Dispatch.call(cells, "Select");
            	Dispatch.put(cells,  "Width" ,  new  Variant(columnWidth));
        	}
        }
    }  
    
    // word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell  
    // 另外下标从1开始  
    public void insertTableNew(int row, int column,String[][] dataArr,boolean orientationFlg) {  
    	
        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
        String ret= Dispatch.get(selection, "Orientation").toString();
        if(orientationFlg){
        	// true 纵向
        	Dispatch.put(selection, "Orientation", 0);//设置为纵向
        }else{
        	Dispatch.put(selection, "Orientation", 1);//设置为横向
        }
        Dispatch.call(selection, "MoveDown"); // 游标往下一行
//        Dispatch.call(selection, "MoveLeft");
         
        Dispatch alignment = Dispatch.get(selection,  "ParagraphFormat" ).toDispatch();
        Dispatch.put(alignment,  "Alignment" , "1");
		// 建立表格  
		Dispatch tables = Dispatch.get(document, "Tables").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 rows = Dispatch.get(newTable,  "rows" ).toDispatch();
        int rowHeight = 25;
        int columnWidth = 200;
        Dispatch.put(rows,  "Height" ,  new  Variant(rowHeight));
    	for (int j = 1; j <= column; j++) {// 每一列
    		 for (int i = 1; i <= row; i++) { // 循环取出每一行 
        		//设置列宽      列宽取值范围:10<columnWidth 默认值:120
	            Dispatch cells = Dispatch.call(newTable, "Cell", new Variant(i), new Variant(j)).toDispatch();  
            	Dispatch.call(cells, "Select");
            	Dispatch.put(cells, "VerticalAlignment", new Variant(1));// 对齐方式为垂直对齐( 0-顶端, 1-居中, 3-底端 )
            	
            	if(j==1){
            		columnWidth = 60;
            	}else if(j==2){
            		columnWidth = 130;
            	}else if(j==3){
            		columnWidth = 90;
            	}else if(j==4){
            		columnWidth = 80;
            	}else if(j==5){
            		columnWidth = 70;
            	}
            	Dispatch.put(cells,  "Width" ,  new  Variant(columnWidth));
            	putTxtToCell(newTable, i, j, dataArr[i-1][j-1]); 
            }
        }
        Dispatch.call(selection, "MoveDown"); // 游标往下一行 
    }
    
      
    /** 
     * 在指定的单元格里填写数据 
     * 
     * @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();// 文档中最后一个table  
        mergeCell(table, 1, 1, 1, 2);// 将table 中x=1,y=1 与x=1,y=2的两个单元格合并  
    }  
    
    // 列合并(上下合并)
    public void mergeCellBYCELL() {  
        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();// 文档中最后一个table  
        Dispatch cols = Dispatch.get(table, "Columns").toDispatch(); // 此表的所有列,  
        int colCount = Dispatch.get(cols, "Count").changeType(  
                Variant.VariantInt).getInt();// 一共有多少列 实际上这个数==column  
        
        Dispatch col = Dispatch.call(cols, "Item", new Variant(1)).toDispatch();  
        Dispatch cells = Dispatch.get(col, "Cells").toDispatch();// 当前列中单元格
        int cellCount = Dispatch.get(cells, "Count").changeType(Variant.VariantInt).getInt();// 当前列中单元格数 实际上这个数等于row  
 
        // 合并列
        for(int k = 1; k <= 2; k++){
	        for (int j =1; j <= cellCount; j++) {// 每一列中的单元格数  
	        	Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(j),  new Variant(k)).toDispatch();
		        Dispatch range=Dispatch.get(cell1,"Range").toDispatch(); 
		        String data=Dispatch.get(range,"Text").getString();
		        data = data.substring(0, data.length()-2);  
		        for(int i = j+1; i <= cellCount; i++){
		        	Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(i),  new Variant(k)).toDispatch();
			        Dispatch range2=Dispatch.get(cell2,"Range").toDispatch(); 
			        String data2=Dispatch.get(range2,"Text").getString();
			        data2 = data2.substring(0, data2.length()-2);
			       
			        if(data2.equals(data)){
			        	if(i==cellCount){
			        		for(int m=j;m<=i;m++){
				        		putTxtToCell(table,m, k,"");
				        	}
				        	mergeCell(table, j , k, i, k);
				        	putTxtToCell(table,j, k,data);
				        	data = data2;
				        	j=i+1;
			        	}
			        	
			        }else if(i==j+1){
			        	data = data2;
			        	j=i;
			        }else{
			        	for(int m=j;m<i;m++){
			        		putTxtToCell(table,m, k,"");
			        	}
			        	mergeCell(table, j , k, i-1, k);
			        	putTxtToCell(table,j, k,data);
			        	data = data2;
			        	j=i;
			        }
		        }
		        
	        }
        }
        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
        Dispatch.call(selection, "MoveDown"); // 游标往下一行   
    } 
   
    public void mergeCellTL() {
        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();// 文档中最后一个table
        Dispatch cols = Dispatch.get(table, "Columns").toDispatch(); // 此表的所有列,  
        int colCount = Dispatch.get(cols, "Count").changeType(  
                Variant.VariantInt).getInt();// 一共有多少列 实际上这个数==column    
        //for (int i = 1; i <= colCount; i++) { // 循环取出每一列  
            Dispatch col = Dispatch.call(cols, "Item", new Variant(1)).toDispatch();  
            Dispatch cells = Dispatch.get(col, "Cells").toDispatch();// 当前列中单元格
            int cellCount = Dispatch.get(cells, "Count").changeType(Variant.VariantInt).getInt();// 当前列中单元格数 实际上这个数等于row  
            List<Integer> listInt = new ArrayList<>();
            // 合并行
            for (int j = 1; j <= 2; j++) {// 每一列中的单元格数  
	            for (int k = 1; k <= cellCount; k++) {// 每一列中的单元格数
	            	if(j==1){
	            		listInt.add(k);// 存储行编号
	            	}
	            	Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(k),  new Variant(j)).toDispatch();
	            	Dispatch range=Dispatch.get(cell1,"Range").toDispatch(); 
	    	        String data=Dispatch.get(range,"Text").getString();
	    	        data = data.substring(0, data.length()-2);
	    	        for (int m = k+1; m <= cellCount; m++) {// 每一列中的单元格数  
		    	        Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(m),  new Variant(j)).toDispatch();
		    	        Dispatch range2=Dispatch.get(cell2,"Range").toDispatch(); 
		    	        String data2=Dispatch.get(range2,"Text").getString();
		    	        data2 = data2.substring(0, data2.length()-2);
		    	        if(data2.equals(data)){
		    	        	putTxtToCell(table,k , j,"");
		    	        	putTxtToCell(table,m, j,"");
		    	        }else if(m > k+1){
		    	        	mergeCell(table, k , j, m-1, j);
		    	        	putTxtToCell(table,k, j,data);
		    	        	k=m-1;
		    	        	break;
		    	        }else{
		    	        	break;
		    	        }
	            	} 
	            }
            }
            
            // 合并列
            for (int j :listInt) {// 每一列中的单元格数  
            	Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(j),  new Variant(1)).toDispatch();  
    	        //Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(2),  new Variant(i)).toDispatch();
    	        Dispatch range=Dispatch.get(cell1,"Range").toDispatch(); 
    	        String data=Dispatch.get(range,"Text").getString();
    	        data = data.substring(0, data.length()-2);  
    	        Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(j),  new Variant(2)).toDispatch();
    	        Dispatch range2=Dispatch.get(cell2,"Range").toDispatch(); 
    	        String data2=Dispatch.get(range2,"Text").getString();
    	        data2 = data2.substring(0, data2.length()-2);
    	        if(data2.equals(data)){
    	        	putTxtToCell(table,j, 1,"");
    	        	putTxtToCell(table,j, 2,"");
    	        	mergeCell(table, j , 1, j, 2);
    	        	putTxtToCell(table,j, 1,data);
    	        }
            }
            Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象  
            Dispatch.call(selection, "MoveDown"); // 游标往下一行 
    }  

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值