另外,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应用程序中,这使在应用程序中实现功能的嵌入成为可能。
