.NET 中 操作excel 系列--copy功能.

来源:互联网 发布:linux网卡设置命令 编辑:程序博客网 时间:2024/06/14 09:47

///   <summary>
        ///   插行(在指定WorkSheet指定行上面插入指定数量行)
        ///   </summary>
        ///   <param   name= "rowIndex ">从哪行开始插入</param>
        ///   <param name="funcColumnIndex">函数所在列</param>
        ///   <param   name= "count ">插入数量 </param>
        public void InsertRows(int rowIndex,int funcColumnIndex, int count)
        {
            Microsoft.Office.Interop.Excel.Application excel = null;
            Microsoft.Office.Interop.Excel.Workbooks wbs = null;
            Microsoft.Office.Interop.Excel.Workbook wb = null;
            Microsoft.Office.Interop.Excel.Worksheet ws = null;
            object Nothing = System.Reflection.Missing.Value;
             try 
            { 
            excel=new Microsoft.Office.Interop.Excel.Application(); 
            excel.UserControl=true; 
            excel.DisplayAlerts=false;
            excel.Application.Workbooks.Open("D:\\TEST.xls", Nothing, Nothing, Nothing, Nothing, 
            Nothing,Nothing,Nothing,Nothing,Nothing, 
            Nothing,Nothing,Nothing); 

            wbs=excel.Workbooks; 
            wb=wbs[1];  //每一个workbook
            ws=(Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets["Sheet1"];//表格名这 Sheeet1
          
         
                Range range = (Range)ws.Rows[rowIndex,Type.Missing];
                Range sourceRg = ((Range)range.Cells[1, funcColumnIndex]);//将被复制的函数
                for (int i = 0; i < count; i++)
                {
                    range.Insert(XlInsertShiftDirection.xlShiftDown,0);//插入新行
                    for (int j = 1; j < funcColumnIndex; j++)
                    {//给前面的几个单元格随便输入一些值.
                        ws.Cells[rowIndex + i, j] = i + j;
                    }
                    sourceRg.Copy(ws.Cells[rowIndex + i, funcColumnIndex]);//复制到目标单元格(最后一列)
                }
            }
            catch (Exception e)
            {               
                throw e;
            }
  }

 

同理,excel 的worksheet 和 row 都可以这样拷贝.果要只拷贝单元格中的文本呢?那就要用到windows剪贴板了,下面是从网上拷贝下来的.

 xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1);

Excel.Range range = xlSheet.get_Range("A1", Type.Missing);range.Value = "123";

System.Windows.Forms.Clipboard.SetDataObject(range.Value.ToString());

Excel.Worksheet sheet1 = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(2);Excel.Range range1 = sheet1.get_Range("B1", Type.Missing);sheet1.Paste(range1, false);要注意的是,这种方式只能选一个单元格,复制一个,不能选定一批单元格进行复制。

 

原创粉丝点击