C#.NET綁定Office簡單介紹
C#.NET綁定Office晚期綁定
與早期綁定不同,C#.NET綁定Office晚期綁定要等到運行時才會將屬性和方法調(diào)用綁定到它們的對象。為此,目標(biāo)對象必須實現(xiàn)一個特殊的 COM 接口:IDispatch。利用 IDispatch::GetIDsOfNames 方法,Visual C# 可以詢問對象支持哪些方法和屬性,然后,IDispatch::Invoke 方法允許 Visual C# 調(diào)用這些方法和屬性。這種晚期綁定的優(yōu)點是:它消除了早期綁定所固有的某些版本依賴性。然而,它也有以下缺點:省略了對自動化代碼完整性的編譯時檢查,也不提供“智能感知”功能(該功能可提供有助于正確調(diào)用方法和屬性的提示)。
要在 Visual C# 中使用C#.NET綁定Office晚期綁定,請使用 System.Type.InvokeMember 方法。此方法調(diào)用 IDispatch::GetIDsOfNames 和 IDispatch::Invoke 來綁定到自動化服務(wù)器的方法和屬性?!?/P>
創(chuàng)建使用晚期綁定的自動化客戶端
啟動 Microsoft Visual Studio .NET。在文件菜單上,單擊新建,然后單擊項目。從 Visual C# 項目類型中選擇 Windows 應(yīng)用程序。默認(rèn)情況下會創(chuàng)建 Form1。
在視圖菜單上,選擇工具箱以顯示工具箱,然后向 Form1 添加一個按鈕。
雙擊 Button1。將出現(xiàn)該窗體的代碼窗口。
在代碼窗口中,將以下代碼:
- private void button1_Click(object sender, System.EventArgs e)
- {
- }
- 替換為:private void button1_Click(object sender, System.EventArgs e)
- {
- object objApp_Late;
- object objBook_Late;
- object objBooks_Late;
- object objSheets_Late;
- object objSheet_Late;
- object objRange_Late;
- object[] Parameters;
- try
- {
- // Instantiate Excel.
- objApp_Late = (object)new Excel.Application();
- //Get the workbooks collection.
- objBooks_Late = objApp_Late.GetType().InvokeMember( "Workbooks",
- BindingFlags.GetProperty, null, objApp_Late, null );
- //Add a new workbook.
- objBook_Late = objBooks_Late.GetType().InvokeMember( "Add",
- BindingFlags.InvokeMethod, null, objBooks_Late, null );
- //Get the worksheets collection.
- objSheets_Late = objBook_Late.GetType().InvokeMember( "Worksheets",
- BindingFlags.GetProperty, null, objBook_Late, null );
- //Get the first worksheet.
- Parameters = new Object[1];
- Parameters[0] = 1;
- objSheet_Late = objSheets_Late.GetType().InvokeMember( "Item",
- BindingFlags.GetProperty, null, objSheets_Late, Parameters );
- //Get a range object that contains cell A1.
- Parameters = new Object[2];
- Parameters[0] = "A1";
- Parameters[1] = Missing.Value;
- objRange_Late = objSheet_Late.GetType().InvokeMember( "Range",
- BindingFlags.GetProperty, null, objSheet_Late, Parameters );
- //Write "Hello, World!" in cell A1.
- Parameters = new Object[1];
- Parameters[0] = "Hello, World!";
- objRange_Late.GetType().InvokeMember( "Value", BindingFlags.SetProperty,
- null, objRange_Late, Parameters );
- //Return control of Excel to the user.
- Parameters = new Object[1];
- Parameters[0] = true;
- objApp_Late.GetType().InvokeMember( "Visible", BindingFlags.SetProperty,
- null, objApp_Late, Parameters );
- objApp_Late.GetType().InvokeMember( "UserControl", BindingFlags.SetProperty,
- null, objApp_Late, Parameters );
- }
- catch( Exception theException )
- {
- String errorMessage;
- errorMessage = "Error: ";
- errorMessage = String.Concat( errorMessage, theException.Message );
- errorMessage = String.Concat( errorMessage, " Line: " );
- errorMessage = String.Concat( errorMessage, theException.Source );
- MessageBox.Show( errorMessage, "Error" );
- }
- }
【編輯推薦】