文章編號: 301659 - 上次校閱: 2007年1月17日 - 版次: 3.2

HOWTO:讓 Microsoft Word 由 Visual C# .NET 自動執行合併列印

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。

在此頁中

全部展開 | 全部摺疊

結論

本文示範如何讓 Word 使用 Microsoft Visual C# .NET 自動建立一個合併列印的文件。

其他相關資訊

自動化處理程序能讓以 Visual C# .NET 等語言撰寫的應用程式,透過程式控制其他應用程式。Word 自動化能讓您執行一些動作,例如,建立新文件、新增文件文字以及製作文件格式。使用 Word 和其他 Microsoft Office 應用程式時,幾乎所有透過使用者介面手動執行的動作,也都能透過程式來自動化執行。

Word 透過物件模型展現程式功能。物件模型是類別和方法的集合,可做為 Word 邏輯元件的副本。例如,Application 物件、Document 物件和 Paragraph 物件,均含有 Word 中這些元件的功能。如果要從 Visual C# .NET 存取物件模型,您可以將專案參考設定至型別程式庫。

本文示範如何將 Visual C# .NET 的適當專案參考設定至 Word 型別程式庫,並且提供自動執行 Word 的程式碼範例。

建置自動化範例

  1. 啟動 Microsoft Visual Studio .NET。在 [檔案] 功能表中,按一下 [新增],再按一下 [專案]。從 Visual C# 專案型別中,選取 [Windows 應用程式]。依照預設,會建立 Form1
  2. 將參考新增至 [Microsoft Access Object Library]。如果要執行這項操作,請遵循以下步驟:
    1. [專案] 功能表上,按一下 [加入參考]
    2. [COM] 索引標籤中找到 [Microsoft Word Object Library],按一下 [選取]
    3. [加入參考] 對話方塊中按一下 [確定],表示接受您的選擇。
  3. [檢視] 功能表中,選取 [工具箱] 以顯示「工具箱」,然後在 [Form1] 新增一個按鈕 。
  4. 按兩下 [Button1]。表單的程式碼視窗便會顯示。
  5. 在程式碼視窗中,將下列程式碼
      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");
    } 
    					
  6. 在 Form1.cs 頂端加入下列程式碼:
    using Word = Microsoft.Office.Interop.Word;
    					
  7. 按 F5 建置及執行程式。
  8. 按一下 [Button1] 啟動「Word 自動化」並且執行合併列印。

?考

如需詳細資訊,請參閱下列 Microsoft Developer Network (MSDN) 網站:
Microsoft Office Development with Visual Studio
http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx (http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx)
如需使用 Microsoft Visual Basic 自動執行 Word 的詳細資訊,請按一下下列的文件編號,檢視 Microsoft Knowledge Base 中的文件:
285332? (http://support.microsoft.com/kb/285332/ZH-TW/ ) HOWTO:Automate Word 2002 with Visual Basic to Create a Mail Merge
220607? (http://support.microsoft.com/kb/220607/ZH-TW/ ) HOWTO:Automate Microsoft Word to Perform Mail Merge from Visual Basic
301656? (http://support.microsoft.com/kb/301656/ZH-TW/ ) HOWTO:Automate Microsoft Word to Perform a Mail Merge from Visual Basic .NET

這篇文章中的資訊適用於:
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Word 2002 Standard Edition
  • Microsoft Visual C# .NET 2003 標準版
關鍵字:?
kbpia kbautomation kbhowto KB301659
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。