有关本文的 Microsoft Visual Basic .NET 版本,请 参阅301656。
摘要
本文演示如何使用 Microsoft Visual C# 2005 或 Microsoft Visual C# .NET 自动执行 Microsoft Word 创建邮件合并文档。
更多信息
自动化是一个过程,允许使用 Visual C# 2005 或 Visual C# .NET 等语言编写的应用程序以编程方式控制其他应用程序。 通过 Word 自动化,可以执行创建新文档、向文档添加文本和设置文档格式等操作。 使用 Word 和其他 Microsoft Office 应用程序,几乎可以通过用户界面手动执行的所有操作也可以使用自动化以编程方式执行。
Word 通过对象模型公开此编程功能。 对象模型是类和方法的集合,它们充当 Word 逻辑组件的对应项。 例如,有一个 Application 对象、一个 Document 对象和一个 Paragraph 对象,其中每个对象都包含 Word 中这些组件的功能。 若要从 Visual C# 2005 或 Visual C# .NET 访问对象模型,可以设置对类型库的项目引用。
本文演示如何为 Visual C# .NET 设置对 Word 类型库的适当项目引用,并提供用于自动执行 Word 的示例代码。
生成自动化示例
启动 Microsoft Visual Studio 2005 或 Microsoft Visual Studio .NET。
在“文件”菜单上,单击“新建”,然后单击“项目”。 从 Visual C# 项目类型中选择 Windows 应用程序。 默认情况下会创建 Form1。
在 Visual Studio 2005 中添加对 Microsoft Word 11.0 对象库 或 Visual Studio .NET 中的 Microsoft Word 对象库的引用。 为此,请按照下列步骤操作:
在"项目"菜单上单击"添加引用"。
在“COM”选项卡上,找到 Microsoft Word 对象库,然后单击“选择”。
在 Visual Studio 2005 中,在 COM 选项卡上找到 Microsoft Word 11.0 对象库。
注意 Microsoft Office 2003 包括主要互操作程序集 (PIA) 。 Microsoft Office XP 不包括 PIA,但可以下载它们。
在“添加引用”对话框中单击“确定”以接受所选内容。
在“视图”菜单上,选择“工具箱”以显示工具箱,然后将按钮添加到 Form1。
双击 Button1。 将显示窗体的代码窗口。
在代码窗口中,替换以下代码
private void button1_Click(object sender, System.EventArgs e) { }
与:
Word.Application wrdApp; Word._Document wrdDoc; Object oMissing = System.Reflection.Missing.Value; Object oFalse = false; private void InsertLines(int LineNum) { int iCount; // Insert "LineNum" blank lines. for(iCount = 1; iCount<=LineNum; iCount++) { wrdApp.Selection.TypeParagraph(); } } private void FillRow(Word._Document oDoc, int Row, string Text1, string Text2, string Text3, string Text4) { // Insert the data into the specific cell. oDoc.Tables[1].Cell(Row,1).Range.InsertAfter(Text1); oDoc.Tables[1].Cell(Row,2).Range.InsertAfter(Text2); oDoc.Tables[1].Cell(Row,3).Range.InsertAfter(Text3); oDoc.Tables[1].Cell(Row,4).Range.InsertAfter(Text4); } private void CreateMailMergeDataFile() { Word._Document oDataDoc; int iCount; Object oName = "C:\\DataDoc.doc"; Object oHeader = "FirstName, LastName, Address, CityStateZip"; wrdDoc.MailMerge.CreateDataSource(ref oName,ref oMissing, ref oMissing,ref oHeader, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Open the file to insert data. oDataDoc = wrdApp.Documents.Open(ref oName,ref oMissing, ref oMissing, ref oMissing,ref oMissing,ref oMissing, ref oMissing,ref oMissing,ref oMissing,ref oMissing, ref oMissing,ref oMissing,ref oMissing,ref oMissing, ref oMissing/*, ref oMissing */); for (iCount=1; iCount<=2; iCount++) { oDataDoc.Tables[1].Rows.Add(ref oMissing); } // Fill in the data. FillRow(oDataDoc, 2, "Steve", "DeBroux", "4567 Main Street", "Buffalo, NY 98052"); FillRow(oDataDoc, 3, "Jan", "Miksovsky", "1234 5th Street", "Charlotte, NC 98765"); FillRow(oDataDoc, 4, "Brian", "Valentine", "12348 78th Street Apt. 214", "Lubbock, TX 25874"); // Save and close the file. oDataDoc.Save(); oDataDoc.Close(ref oFalse, ref oMissing, ref oMissing); } private void button1_Click(object sender, System.EventArgs e) { Word.Selection wrdSelection; Word.MailMerge wrdMailMerge; Word.MailMergeFields wrdMergeFields; Word.Table wrdTable; string StrToAdd; // Create an instance of Word and make it visible. wrdApp = new Word.Application(); wrdApp.Visible = true; // Add a new document. wrdDoc = wrdApp.Documents.Add(ref oMissing,ref oMissing, ref oMissing,ref oMissing); wrdDoc.Select(); wrdSelection = wrdApp.Selection; wrdMailMerge = wrdDoc.MailMerge; // Create a MailMerge Data file. CreateMailMergeDataFile(); // Create a string and insert it into the document. StrToAdd = "State University\r\nElectrical Engineering Department"; wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; wrdSelection.TypeText(StrToAdd); InsertLines(4); // Insert merge data. wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; wrdMergeFields = wrdMailMerge.Fields; wrdMergeFields.Add(wrdSelection.Range, "FirstName"); wrdSelection.TypeText(" "); wrdMergeFields.Add(wrdSelection.Range, "LastName"); wrdSelection.TypeParagraph(); wrdMergeFields.Add(wrdSelection.Range, "Address"); wrdSelection.TypeParagraph(); wrdMergeFields.Add(wrdSelection.Range, "CityStateZip"); InsertLines(2); // Right justify the line and insert a date field // with the current date. wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; Object objDate = "dddd, MMMM dd, yyyy"; wrdSelection.InsertDateTime(ref objDate,ref oFalse,ref oMissing, ref oMissing, ref oMissing); InsertLines(2); // Justify the rest of the document. wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; wrdSelection.TypeText("Dear "); wrdMergeFields.Add(wrdSelection.Range, "FirstName"); wrdSelection.TypeText(","); InsertLines(2); // Create a string and insert it into the document. StrToAdd = "Thank you for your recent request for next " + "semester's class schedule for the Electrical " + "Engineering Department. Enclosed with this " + "letter is a booklet containing all the classes " + "offered next semester at State University. " + "Several new classes will be offered in the " + "Electrical Engineering Department next semester. " + "These classes are listed below."; wrdSelection.TypeText(StrToAdd); InsertLines(2); // Insert a new table with 9 rows and 4 columns. wrdTable = wrdDoc.Tables.Add(wrdSelection.Range,9,4, ref oMissing, ref oMissing); // Set the column widths. wrdTable.Columns[1].SetWidth(51, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone); // Set the shading on the first row to light gray. wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex = Word.WdColorIndex.wdGray25; // Bold the first row. wrdTable.Rows[1].Range.Bold = 1; // Center the text in Cell (1,1). wrdTable.Cell(1, 1).Range.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; // Fill each row of the table with data. FillRow(wrdDoc, 1, "Class Number", "Class Name", "Class Time", "Instructor"); FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II", "1:00-2:00 M,W,F", "Dr. Jensen"); FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I", "10:00-11:30 T,T", "Dr. Crump"); FillRow( wrdDoc, 4, "EE300", "Feedback Control Systems", "9:00-10:00 M,W,F", "Dr. Murdy"); FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design", "9:00-10:30 T,T", "Dr. Alley"); FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems", "9:00-10:30 T,T", "Dr. Taylor"); FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory", "1:00-2:30 T,T", "Dr. Lee"); FillRow(wrdDoc, 8, "EE450", "Plasma Theory", "1:00-2:00 M,W,F", "Dr. Davis"); FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design", "3:00-4:00 M,W,F", "Dr. Ellison"); // Go to the end of the document. Object oConst1 = Word.WdGoToItem.wdGoToLine; Object oConst2 = Word.WdGoToDirection.wdGoToLast; wrdApp.Selection.GoTo(ref oConst1,ref oConst2,ref oMissing,ref oMissing); InsertLines(2); // Create a string and insert it into the document. StrToAdd = "For additional information regarding the " + "Department of Electrical Engineering, " + "you can visit our Web site at "; wrdSelection.TypeText(StrToAdd); // Insert a hyperlink to the Web page. Object oAddress = "http://www.ee.stateu.tld"; Object oRange = wrdSelection.Range; wrdSelection.Hyperlinks.Add(oRange, ref oAddress,ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Create a string and insert it into the document StrToAdd = ". Thank you for your interest in the classes " + "offered in the Department of Electrical " + "Engineering. If you have any other questions, " + "please feel free to give us a call at " + "555-1212.\r\n\r\n" + "Sincerely,\r\n\r\n" + "Kathryn M. Hinsch\r\n" + "Department of Electrical Engineering \r\n"; wrdSelection.TypeText(StrToAdd); // Perform mail merge. wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument; wrdMailMerge.Execute(ref oFalse); // Close the original form document. wrdDoc.Saved = true; wrdDoc.Close(ref oFalse,ref oMissing,ref oMissing); // Release References. wrdSelection = null; wrdMailMerge = null; wrdMergeFields = null; wrdDoc = null; wrdApp = null; // Clean up temp file. System.IO.File.Delete("C:\\DataDoc.doc"); }
注意 必须在 Visual Studio 2005 中更改代码。 默认情况下,在创建Windows 窗体项目时,Visual C# 会向项目添加一个窗体。 该窗体名为 Form1。 表示窗体的两个文件名为 Form1.cs 和 Form1.designer.cs。 在 Form1.cs 中编写代码。 Form1.designer.cs 文件是Windows 窗体设计器写入代码的位置,该代码通过拖放工具箱中的控件来实现执行的所有操作。
有关 Visual C# 2005 中Windows 窗体设计器的详细信息,请访问以下 Microsoft 开发人员网络 (MSDN) 网站:创建项目 (Visual C#) 注意 Microsoft Office Word 2003 具有文档的 Open 方法的附加参数。 如果使用的是 Word 2003 PIA,请删除 Open 方法的附加参数的注释表示法。
将以下内容添加到 Form1.cs 的顶部:
using Word = Microsoft.Office.Interop.Word;
按 F5 生成并运行程序。
单击 Button1 启动 Word 自动化并执行邮件合并。
参考
有关详细信息,请访问以下 Microsoft 开发人员网络 (MSDN) 网站:Microsoft Office Development with Visual Studio Microsoft Office Development with Visual Studio
有关详细信息,请单击以下文章编号以查看 Microsoft 知识库中的文章:
285332 如何使用 Visual Basic 自动执行 Word 2002 以创建邮件合并