下面的代碼說明如何一個Sheet上的選定內容拷貝到另一個Sheet上:
ThisApplication = new Excel.Application(); ThisWorkbook = ThisApplication.Workbooks.Open("z:\\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); ThisApplication.DisplayAlerts = false; xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1); Excel.Range range = xlSheet.get_Range("A1", Type.Missing); range.Value = "123"; Excel.Worksheet sheet1 = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(2); Excel.Range range1 = sheet1.get_Range("B1", Type.Missing); range.Copy(range1); ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
可以看到,核心的代碼是很簡單的,就是選定一個源區域,然後指定另一個目標區域,調用源區域的Copy方法將內容整個復制到目標區域,但是你會發現是連單元格的格式等屬性一並拷貝過去的,如果要只拷貝單元格中的文本呢?那就要用到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);
要注意的是,這種方式只能選一個單元格,復制一個,不能選定一批單元格進行復制。
上面的例子只給出了主要部分的代碼,其他的像銷毀Excel進程等操作請參考前面的幾篇Excel作報表的隨筆。