原文出處http://www.digicul.com/article/135/135_9693.html
開發者經常考慮應該加強代碼重用的力度,因為有些任務對他們來說就是利用現有的程式。一個典型的例子就是使用Microsoft Office套裝的一個或多個程式,例如,你可以利用Excel表單建立一個圖表或者一個财務報表,或建立一個包含使用者注冊資訊的Word文檔,在這篇文 章中,我就是把Word嵌入到.NET程式中,以下就是實作過程。
程式的編制模式
Microsoft把.NET作為最終的解決方案似乎有些出人意料,因為在Microsoft Office的程式編制模式中并沒有使用它,Office仍在使用以前的VBA(Visual Basic for Applications)模式,更重要的就是VBA是基于COM(Component Object Model)的,是以Microsoft Office将與.NET不能同互相通訊。但是,.NET擁有一項被稱為COM互操作性(COM interop)的功能,它提供了一個可調用的檔案夾來實作.NET和COM互相操作。
如果你使用的是Visual Studio .NET IDE,.NET是通過在運作期間的一個可調用檔案夾來實作COM元件的使用,具體的步驟如下:
1、 從Project菜單中選擇Add Reference
2、 選擇Add Reference視窗下的COM分頁,輕按兩下合适的類型庫檔案。
3、 選擇OK完成引用的添加。
這時,Visual Studio .NET會把COM類型庫檔案的對象(objects)和成員(members)轉化到相應的.NET程式集中。一旦生成.NET程式集,這些COM對象 和成員就像.NET自己的類一樣,你就可以很容易執行個體化一個類或調用一個成員。你也可以逆其道而行之,在基于COM的應用程式中使用.NET程式集,但這 些超出了我們的讨論範圍。
可以用下面的一個例子來進一步說明這一過程。讓我們在一個簡單的.NET Windows Form(窗體)中建立一個Word文檔。
使用Microsoft Word
首先,在Visual Studio .NET中建立一個新的工程,将一個引用(reference)添加到Microsoft Word類型庫中,我使用的是Microsoft Word 2003,是以類型庫是Microsoft Word 11.0 Object Library。添加完引用(reference)後,就可以在代碼中使用Word對象。清單A給出了VB.NET語言的例子,當使用者按下Windows Form(窗體)中一個按鈕時,程式将從本地的驅動器中打開一個已經存在的Word文檔。
表 A
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Word
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim strFileName As String
Dim word As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document
Try
doc = word.Documents.Open("c:/test.doc")
doc.Activate()
Catch ex As COMException
MessageBox.Show("Error accessing Word document.")
End Try
End Sub
End Class
請注意代碼中下面的幾個地方:
· System.Runtime.InteropServices 的名稱空間将被引入并與COM和.NET共同運作。它包含了COMException類。
· Word對象的.NET檔案夾是包含在Microsoft.Office.Interop.Word的名稱空間中的(就是剛才添加到工程中的引用)。
· 用Word 名稱空間的Apllication類來通路Word應用程式。
· 用Word 名稱空間中的文檔類來操作Word文檔。
· 應用程式中的文檔屬性——Open函數加載已存在的文檔,同時它還包含了一個Close函數。
· Document類的Activate函數用來在新的Word視窗中打開文檔。
· 通路Word文檔的代碼包含在Try/Catch子產品中,它可以通過COMException類捕捉COM的錯誤,用MessageBox.Show函數替代了Office VBA MsgBox函數。
表B就是相應的C#代碼
<script type="text/javascript"><!-- google_ad_client = "pub-3087437763491028"; google_ad_width = 300; google_ad_height = 250; google_ad_format = "300x250_as"; google_ad_type = "text_image"; google_ad_channel ="5235125340"; google_color_border = "FAFAFA"; google_color_bg = "FAFAFA"; google_color_link = "0000FF"; google_color_text = "000000"; google_color_url = "008000"; //--></script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/expansion_embed.js"></script> <script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"></script> <script>google_protectAndRun("ads_core.google_render_ad", google_handleError, google_re</script> 表 B using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Word; namespace BuilderWordIntegration { public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; static void Main() { System.Windows.Forms.Application.Run(new Form1()); } private void button1_Click(object sender, System.EventArgs e) { Microsoft.Office.Interop.Word.Application word = null; Microsoft.Office.Interop.Word.Document doc = null; try { word = new Microsoft.Office.Interop.Word.Application(); object fileName = "c://test.doc"; object falseValue = false; object trueValue = true; object missing = Type.Missing; word.Visible = true; word.Activate(); doc = word.Documents.Open(ref fileName, ref missing, ref trueValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Activate(); } catch (COMException ex) { MessageBox.Show("Error accessing Word document."); } } } } C#與 VB.NET代碼的不同點就是在Documents.Open的調用上,C# 要求傳遞所有的參數,這些參數必須都是對象的引用。由于這一原因,必須先建立對象并指派,并把所有的引用(ref)傳遞給函數call,另外,由于許多參 數的值是null,是以在這裡使用了Type.Missing值,實際上Word 應用程式隻能被它自己的Activate函數激活,要想顯示它,還要把它的Visible參數設為true。最後要提醒的就是C#語言是把反斜線(/)識 别為換行符,在字元串中作為字元使用時要用雙反斜線(//)。 利用.NET對文檔進行操作 你可以打開已經存在的Word文檔,也可以建立一個Word文檔用來存放應用程式的資料。Documents的Add函數提供了建立Word文檔的功能,下面的VB.NET程式行使用在先前的例子中已經建立的對象。 word.Documents.Add() 另外,Word 對象子產品還具有許多可以實作對Word文檔中的文本操作的多個函數和屬性,在表C中VB.NET的例子中,當按鈕按下時建立一個文檔,然後在文檔的開始部分插入文本(隻給出了按鈕部分的代碼)。 表 C Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim strFileName As String Dim word As New Microsoft.Office.Interop.Word.Application Dim doc As Microsoft.Office.Interop.Word.Document Try doc = word.Documents.Add() Dim insertText As String = "Text inserted at the beginning of the document." Dim range As Microsoft.Office.Interop.Word.Range = doc.Range(Start:=0, End:=0) range.Text = insertText doc.SaveAs("c:/test2.doc") Catch ex As COMException MessageBox.Show("Error accessing Word document.") Finally doc.Close(True) End Try End Sub 在這個例子中請注意以下幾點: Word.Range對象可以實作對Word文檔中的一段文本進行操作。文本塊的位置是通過文本塊開始和結束的值來确定。在這個例子中,文檔塊的開 始值是指向整個文檔的開始位置,文本塊結束位置的值表明了整個文檔的大小——如果文檔大小為0,則表示文本結束位和開始位置的值相等。 Word.Range 對象的Text屬性可對文本格式進行設定,SaveAs函數允許你使用給定的值對文檔進行儲存。表D為相應的C#代碼。 表D private void button1_Click(object sender, System.EventArgs e) { Microsoft.Office.Interop.Word.Application word = null; Microsoft.Office.Interop.Word.Document doc = null; try { word = new Microsoft.Office.Interop.Word.Application(); object fileName = "c://test3.doc"; object trueValue = true; object missing = Type.Missing; doc = word.Documents.Add(ref missing, ref missing, ref missing, ref trueValue); string insertText = "Text inserted at the beginning of the document."; Microsoft.Office.Interop.Word.Range range = null; object startPosition = 0; object endPosition = 0; range = doc.Range(ref startPosition, ref endPosition); range.Text = insertText; doc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } catch (COMException ex) { MessageBox.Show("Error accessing Word document."); } } 再提醒一次,C#要求指明所有參數的值,是以要使用Type.Missing的值,你可以浏覽Word對象子產品來學習更多的方法(methods)和屬性(properties)。 總結 Microsoft Office是世界上最為流行的辦公軟體,利用.NET 和COM的互操作性可以很容易地将其強大的功能內建到你的.NET應用程式中,這使在應用程式中實作功能的嵌入成為可能。 |