表 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()
