本文演示如何创建和使用自动化操作从 Visual c + +.net 和 Microsoft 基础类 (MFC) Word 文档

自动化是允许以诸如 Visual c + +.net 以编程方式控制其他应用程序的语言编写的应用程序的过程。到 Word 的自动化允许您执行操作 (如创建新文档、 将文本添加到文档,和格式的文档。与 Word 和其他 Microsoft Office 应用程序,几乎所有您可通过用户界面手动执行的操作也可以执行以编程方式通过使用自动化。

Word 会公开一个对象模型通过此编程功能。对象模型是类和方法用作对应于 Word 的逻辑组件的集合。例如对于没有 应用程序 对象、 一个 文档 对象和其中的每个包含在 Word 中的这些组件的功能是 段落 对象。若要访问对象模型从 Visual c + +.net,您可以设置对类型库的项目引用。

生成自动化示例

  1. 请按照下面的 Microsoft 知识库文章,以创建一个基本的自动化客户端的"创建了自动化客户端"一节中的步骤操作:      
    307473                                         (http://support.microsoft.com/kb/307473/EN-US/                        )       HOWTO: 将类型库用于从 Visual c + +.net Office 自动化 
    在文章的第 4 步中选择 Microsoft Word 类型库。Word 2000 的默认位置是 Files\Microsoft Office\Office\Msword9.olb、 Word 2002 的默认位置是 Files\Microsoft Office\Office10\Msword.olb,和 Word 2003 的默认位置是 Files\Microsoft Office\Office11\MSWord.olb。选择以下 Word 接口:      
    • _Application
    • _Document
    • 单元格
    • 单元格
    • 文档
    • 超链接
    • MailMerge
    • MailMergeFields
    • 段落
    • 范围
    • 所选内容
    • 底纹

    在步骤 6 中,Autoprojectdlg.cpp 的开头添加以下的 # include 语句:
    #include "CApplication.h"
    #include "CDocument0.h"
    #include "CDocuments.h"
    #include "CSelection.h"
    #include "CParagraphs.h"
    #include "CTable0.h"
    #include "CTables0.h"
    #include "CRange.h"
    #include "CColumns0.h"
    #include "CColumn.h"
    #include "CRow.h"
    #include "CRows.h"
    #include "CCells.h"
    #include "CCell.h"
    #include "CShading.h"
    #include "CHyperlinks.h"
    #include "CMailMerge.h"
    #include "CMailMergeFields.h"
    					
  2. IDD_AUTOPROJECT_DIALOG 对话框中用鼠标右键单击 运行,然后选择 添加事件处理程序。在事件处理程序向导选择 BN_CLICKED 消息类型,然后单击 添加和编辑
  3. 替换下面的代码
    void CAutoProjectDlg::OnBnClickedRun()
    ( With Visual Studio .NET 1.1 you may not be able to rename the button to anything other than "IDC_Button1". In that case 
    the method will be named CAutoProject::OnBnClickedButton1.)
    {
    	// TO DO: Add your control notification handler code here.
    }
    					
    与:
    void InsertLines(CSelection *pSelection, int NumLines)
    {
    	int iCount;
    
    	// Insert NumLines blank lines.
    	for (iCount = 1; iCount <= NumLines; iCount++)
    		pSelection->TypeParagraph();
    }
    
    void FillRow(CTable0 *pTable,int Row, CString Text1, 
    			 CString Text2, CString Text3, CString Text4)
    {
    	CCell oCell;
    	CRange oRange;
    
    	// Insert data into the specific cell.
    	oCell = pTable->Cell(Row,1);
    	oRange = oCell.get_Range();
    	oRange.InsertAfter(Text1);
    	oCell = pTable->Cell(Row,2);
    	oRange = oCell.get_Range();
    	oRange.InsertAfter(Text2);
    	oCell = pTable->Cell(Row,3);
    	oRange = oCell.get_Range();
    	oRange.InsertAfter(Text3);
    	oCell = pTable->Cell(Row,4);
    	oRange = oCell.get_Range();
    	oRange.InsertAfter(Text4);
    }
    
    void CreateMailMergeDataFile(CApplication *pApp,CDocument0 *pDoc)
    {
      CDocument0 oDataDoc;
      CMailMerge oMailMerge;
      CDocuments oDocs;
      CTables0 oTables;
      CTable0 oTable;
      CRows oRows;
      int iCount;
      COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR),
    				vtFalse((short)FALSE);
      
      // Create a data source that contains the field data at C:\DataDoc.doc.
      oMailMerge = pDoc->get_MailMerge();
      oMailMerge.CreateDataSource(COleVariant("C:\\DataDoc.doc"), 
            vtOptional,vtOptional,
            COleVariant("FirstName, LastName, Address,CityStateZip"),
            vtOptional, vtOptional,vtOptional,vtOptional,vtOptional);
      // Open the file to insert data.
      oDocs = pApp->get_Documents();
    
      //WORD9:
      oDataDoc = oDocs.Open(COleVariant("C:\\DataDoc.doc"), 
           vtOptional,vtOptional,vtOptional,vtOptional,
           vtOptional,vtOptional,vtOptional,vtOptional,
           vtOptional,vtOptional);
    
      //WORD10:
      //oDataDoc = oDocs.Open(COleVariant("C:\\DataDoc.doc"), 
      //     vtOptional,vtOptional,vtOptional,vtOptional,
      //     vtOptional,vtOptional,vtOptional,vtOptional,
      //     vtOptional,vtOptional,vtOptional,vtOptional,
      //	   vtOptional,vtOptional);
    
      //WORD11:
      //oDataDoc = oDocs.Open(COleVariant("C:\\DataDoc.doc"), 
      //     vtOptional,vtOptional,vtOptional,vtOptional,
      //     vtOptional,vtOptional,vtOptional,vtOptional,
      //     vtOptional,vtOptional,vtOptional,vtOptional,
      //	   vtOptional,vtOptional, vtOptional);
    
      oTables = oDataDoc.get_Tables();
      oTable = oTables.Item(1);
      oRows = oTable.get_Rows();
      for (iCount=1; iCount<=2; iCount++)  
        oRows.Add(vtOptional);
    
      // Fill in the data.
      FillRow(&oTable, 2, "Steve", "DeBroux", 
            "4567 Main Street", "Buffalo, NY  98052");
      FillRow(&oTable, 3, "Jan", "Miksovsky", 
            "1234 5th Street", "Charlotte, NC  98765");
      FillRow(&oTable, 4, "Brian", "Valentine", 
            "12348 78th Street  Apt. 214", "Lubbock, TX  25874");
      // Save and close the file.
      oDataDoc.Save();
      oDataDoc.Close(vtFalse,vtOptional,vtOptional);
    } 
    
    void CAutoProjectDlg::OnBnClickedRun() // It may be OnBnClickedButton1()
    {
    	CApplication oWord;
    	CDocuments oDocs;
    	CDocument0 oDoc;
    	CSelection oSelection;
    	CParagraphs oParagraphs;
    	CTables0 oTables;
    	CTable0 oTable;
    	CRange oRange;
    	CColumns0 oColumns;
    	CColumn oColumn;
    	CRows oRows;
    	CRow oRow;
    
    	CCells oCells;
    	CCell oCell; 
    	CShading oShading;
    	CHyperlinks oHyperlinks;
    	CMailMerge oMailMerge;
    
  4.         CMailMergeFields oMailMergeFields;
    
    	COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR),
    		        vtTrue((short)TRUE),
    				vtFalse((short)FALSE);
    	CString StrToAdd;
    
    	// Create an instance of Word.
    	if (!oWord.CreateDispatch("Word.Application")) {
    		AfxMessageBox("Word failed to start!");
    	} else {
    	// Set the visible property.
    	oWord.put_Visible(VARIANT_TRUE);
    	// Add a new document.
    	oDocs = oWord.get_Documents();
    
    	//WORD9:
    	oDoc = oDocs.Add(vtOptional,vtOptional,vtOptional);
    
    	//WORD10 & WORD11:
    	//oDoc = oDocs.Add(vtOptional,vtOptional,vtOptional,vtOptional);
    
    	CreateMailMergeDataFile(&oWord,&oDoc);
    
    	// Add the address header.
    	StrToAdd = "State University\r\nElectrical Engineering "  
    		       "Department";
    	oSelection = oWord.get_Selection();
    
    	oParagraphs = oSelection.get_Paragraphs();
    	oParagraphs.put_Alignment(1);  // 1 = wdAlignParagraphCenter  
    	oSelection.TypeText(StrToAdd);
    
    	InsertLines(&oSelection,4);
    
    	oParagraphs.put_Alignment(0);  // 0 = wdAlignParagraphLeft
    
    
    	oMailMerge = oDoc.get_MailMerge();
    	oMailMergeFields = oMailMerge.get_Fields();
    	oMailMergeFields.Add(oSelection.get_Range(),"FirstName");
    	oSelection.TypeText(" ");
    	oMailMergeFields.Add(oSelection.get_Range(),"LastName");
    	oSelection.TypeParagraph();
    	oMailMergeFields.Add(oSelection.get_Range(),"Address");
    	oSelection.TypeParagraph();
    	oMailMergeFields.Add(oSelection.get_Range(),"CityStateZip");
    
    	InsertLines(&oSelection,4);
    	// Set the paragraph alignment to Right justified.
    	oParagraphs = oSelection.get_Paragraphs();
    
    	oParagraphs.put_Alignment(2);  // 2 = wdAlignParagraphRight
    	// Insert the current date.
    
    	//WORD9:
    	oSelection.InsertDateTime(COleVariant("dddd, MMMM dd, yyyy"), 
    		 vtFalse,vtOptional);
    
    	//WORD10 & WORD11:
    	//oSelection.InsertDateTime(COleVariant("dddd, MMMM dd, yyyy"), 
    	//	 vtFalse,vtOptional,vtOptional,vtOptional);
    
    	InsertLines(&oSelection,2);
    
    	// Reset the justification to Justify.
    
    	oParagraphs = oSelection.get_Paragraphs();
    	oParagraphs.put_Alignment(3);  // 3 = wdAlignParagraphJustify
    
    	oSelection.TypeText("Dear ");
    	oMailMergeFields.Add(oSelection.get_Range(),"FirstName");
    	oSelection.TypeText(",");
    
    	InsertLines(&oSelection,2);
    
    	// Add the body of the message.
    	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.";
    	oSelection.TypeText(StrToAdd);
    
    	InsertLines(&oSelection,2);
    	
    	// Add a new table with 9 rows and 4 columns.
    	oRange = oSelection.get_Range();
    	oTables = oDoc.get_Tables();
    	
    	//WORD9:
    	oTable = oTables.Add(oRange,9,4,vtOptional);
    
    	//WORD10 & WORD11:
    	//oTable = oTables.Add(oRange,9,4,vtOptional,vtOptional);
    
    	// Set the width of each column.
    	oColumns = oTable.get_Columns();
    
    	//BEGIN WORD9:
    	oColumn = oColumns.Item(1);
    	oColumn.put_Width(60.0,0);  // 0 = wdAdjustNone
    	oColumn = oColumns.Item(2);
    	oColumn.put_Width(182.0,0);  // 0 = wdAdjustNone
    	oColumn = oColumns.Item(3);
    	oColumn.put_Width(100.0,0);  // 0 = wdAdjustNone
    	oColumn = oColumns.Item(4);
    	oColumn.put_Width(111.0,0); // 0 = wdAdjustNone
    	//END WORD9
    
            /*
    	//BEGIN WORD10 & WORD11:
    	oColumn = oColumns.Item(1);
    	oColumn.put_Width(60.0);  // 0 = wdAdjustNone
    	oColumn = oColumns.Item(2);
    	oColumn.put_Width(182.0);  // 0 = wdAdjustNone
    	oColumn = oColumns.Item(3);
    	oColumn.put_Width(100.0);  // 0 = wdAdjustNone
    	oColumn = oColumns.Item(4);
    	oColumn.put_Width(111.0);  // 0 = wdAdjustNone
    	//END WORD10 & WORD11
            */ 
    
    	// Set the shading for row 1 to wdGray25.
    	oRows = oTable.get_Rows();
    	oRow = oRows.Item(1);
    	oCells = oRow.get_Cells();
    	oShading = oCells.get_Shading();
    	oShading.put_BackgroundPatternColorIndex(16); // 16 = wdGray25
    
    	// Turn on bold formatting for the first row.
    	oRange = oRow.get_Range();
    	oRange.put_Bold(TRUE);
    
    	// Set the alignment for cell (1,1) to Center.
    	oCell = oTable.Cell(1,1);
    	oRange = oCell.get_Range();
    	oParagraphs = oRange.get_Paragraphs();
    	oParagraphs.put_Alignment(1);  // 1 = wdAlignParagraphCenter
    
    	// Fill in the class schedule data.
    	FillRow(&oTable,1,"Class Number","Class Name", 
    		"Class Time","Instructor");	
    	FillRow(&oTable,2, "EE220", "Introduction to Electronics II",  
    		"1:00-2:00 M,W,F", "Dr. Jensen");
    	FillRow(&oTable,3, "EE230", "Electromagnetic Field Theory I",  
    		"10:00-11:30 T,T", "Dr. Crump");
    	FillRow(&oTable,4, "EE300", "Feedback Control Systems",  
    		"9:00-10:00 M,W,F", "Dr. Murdy");
    	FillRow(&oTable,5, "EE325", "Advanced Digital Design",  
    		"9:00-10:30 T,T", "Dr. Alley");
    	FillRow(&oTable,6, "EE350", "Advanced Communication Systems",  
    		"9:00-10:30 T,T", "Dr. Taylor");
    	FillRow(&oTable,7, "EE400", "Advanced Microwave Theory",  
    		"1:00-2:30 T,T", "Dr. Lee");
    	FillRow(&oTable,8, "EE450", "Plasma Theory",  
    		"1:00-2:00 M,W,F", "Dr. Davis");
    	FillRow(&oTable,9, "EE500", "Principles of VLSI Design",  
    		"3:00-4:00 M,W,F", "Dr. Ellison");
    
    	// Go to the end of the document.
    	oSelection.GoTo(COleVariant((short)3), // 3 = wdGoToLine
    	COleVariant((short)-1),vtOptional,vtOptional);  // -1 = wdGoToLast
    
    	InsertLines(&oSelection,2);
    
    	// Add closing text.
    	StrToAdd = "For additional information regarding the "  
                 "Department of Electrical Engineering, "  
                 "you can visit our website at ";
    	oSelection.TypeText(StrToAdd);
    
    	// Add a hyperlink to the home page.
    	oHyperlinks = oSelection.get_Hyperlinks();
    
            oHyperlinks.Add(oSelection.get_Range(),
                COleVariant("http://www.ee.stateu.tld"),vtOptional,
                vtOptional,vtOptional,vtOptional);
    
    	// Finish adding closing text.
    	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 (999) "  
                 "555-1212.\r\n\r\n"  
                 "Sincerely,\r\n\r\n"  
                 "Kathryn M. Hinsch\r\n" 
                 "Department of Electrical Engineering\r\n";
    	oSelection.TypeText(StrToAdd);
    
    	// Perform mail merge.
    	oMailMerge.put_Destination(0); // 0 = wdSendToNewDocument
    	oMailMerge.Execute(vtFalse);
    
    	// Close the original form document.
    	oDoc.put_Saved(TRUE);
    	oDoc.Close(vtFalse,vtOptional,vtOptional); 
    	}
    }
    					
    注: 此代码为编写,使用 Word 9.0 对象库。当您添加到您的项目的引用,如果选择了 Word 10.0 对象库或的 Word 9.0 对象库而不是 Word 11 时,搜索包含"//WORD10"注释的代码或"/ / WORD11,或 //WORD10 & WORD11and 取消注释行或行是指注释的代码。同样,搜索包含"//WORD9"注释的代码和注释行或行是指注释的代码。     

  5. 一定要实现第 5 步。在上述,即在文章中的"创建自动化客户端"标题下的列表中
    文章 ID 307473"HOWTO: 用于从 Visual c + +.net Office 自动化的类型库。
  6. 按 F5 生成并运行该程序。
  7. 单击 运行。自动化客户端启动 Word,并从邮件合并创建套用信函的一组。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值