在.NET应用程序中轻松使用Microsoft Word功能

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值