你目前正处于脱机状态,正在等待 Internet 重新连接

如何使用 MFC 使 Excel 2002 自动运行、创建新工作簿并设置格式

概要
本文展示了如何使用 Microsoft 基础类 (MFC) 库 4.2 版(随 Microsoft Visual C++ 5.0 和 6.0 版安装)自动运行 Microsoft Excel。

本文介绍了一种使用 OLE Automation 来创建 Microsoft Excel 工作簿并设置格式的技术;该技术引入了一些来自 Microsoft Excel 类型库的方法/属性,用于将数据添加到工作表并设置工作表的格式。

自动运行 Microsoft Excel 2000 和 2002 的说明

本文中的示例代码使用从 Excel 97 对象库 (Excel 8.olb) 中生成的类封装包。只需对这些代码稍作改动,就可以将其应用于使用 Excel 2000 (Excel9.olb) 或 Excel 2002 (Excel.olb) 类封装包的 Automation 客户端。有关结合 Microsoft Excel 2000 或 2002 类型库使用本文介绍的示例代码的更多信息,请单击下面的文章编号,以查看 Microsoft 知识库中相应的文章:
224925 INFO:新版本中的 Office 类型库可能会更改
更多信息
您可以将本文中的代码复制到在 MFC .cpp 文件中定义的事件的消息处理器函数。不过,我们提供这段代码是为了阐述在 Excel8.olb 类型库中定义的 IDispatch 接口和成员函数的使用过程。希望您仔细阅读并理解示例中的代码,进而有能力修改这个示例或自行编写代码来使用 MFC 自动运行 Microsoft Excel 97,这样才能真正从本文中获益。

创建项目的步骤

  1. 执行以下 Microsoft 知识库文章中的第 1 至 12 步,创建一个示例项目,该项目使用在 Excel8.olb 类型库中定义的 IDispatch 接口和成员函数:
    178749如何使用 MFC 和类型库创建自动化项目
  2. 在 AutoProjectDlg.cpp 文件的顶端,添加下面一行:
          #include "excel8.h"					
  3. 将以下代码添加到 AutoProjectDLG.cpp 文件的 CAutoProjectDlg::OnRun() 中:

    示例代码

          // Commonly used OLE variants.      COleVariant                 covTrue((short)TRUE),                 covFalse((short)FALSE),                 covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);      _Application app;      Workbooks books;      _Workbook book;      Worksheets sheets;      _Worksheet sheet;      Range range;      Font font;      Range cols;      // Start Excel and get Application object.      if(!app.CreateDispatch("Excel.Application"))      {       AfxMessageBox("Couldn't start Excel and get Application object.");       return;      }      //Get a new workbook.      books = app.GetWorkbooks();      book = books.Add (covOptional);      //Get the first sheet.      sheets =book.GetSheets();      sheet = sheets.GetItem(COleVariant((short)1));      //Fill cells A1, B1, C1, and D1 one cell at a time with "headers".      range = sheet.GetRange(COleVariant("A1"),COleVariant("A1"));      range.SetValue(COleVariant("First Name"));      range = sheet.GetRange(COleVariant("B1"),COleVariant("B1"));      range.SetValue(COleVariant("Last Name"));      range = sheet.GetRange(COleVariant("C1"),COleVariant("C1"));      range.SetValue(COleVariant("Full Name"));      range = sheet.GetRange(COleVariant("D1"),COleVariant("D1"));      range.SetValue(COleVariant("Salary"));      //Format A1:D1 as bold, vertical alignment = center.      range = sheet.GetRange(COleVariant("A1"), COleVariant("D1"));      font = range.GetFont();      font.SetBold(covTrue);      range.SetVerticalAlignment(               COleVariant((short)-4108));   //xlVAlignCenter = -4108      //Fill A2:B6 with an array of values (First & Last Names).      {         COleSafeArray saRet;         DWORD numElements[]={5,2};   //5x2 element array         saRet.Create(VT_BSTR, 2, numElements);         //Fill the 5x2 SafeArray with the following data:         //   John      Smith         //   Tom       Brown         //   Sue       Thomas         //   Jane      Jones         //   Adam      Johnson         FillSafeArray(L"John", 0, 0, &saRet);         FillSafeArray(L"Smith", 0, 1, &saRet);         FillSafeArray(L"Tom", 1, 0, &saRet);         FillSafeArray(L"Brown", 1, 1, &saRet);         FillSafeArray(L"Sue", 2, 0, &saRet);         FillSafeArray(L"Thomas", 2, 1, &saRet);         FillSafeArray(L"Jane", 3, 0, &saRet);         FillSafeArray(L"Jones", 3, 1, &saRet);         FillSafeArray(L"Adam", 4, 0, &saRet);         FillSafeArray(L"Johnson", 4, 1, &saRet);         range = sheet.GetRange(COleVariant("A2"), COleVariant("B6"));         range.SetValue(COleVariant(saRet));         saRet.Detach();      }      //Fill C2:C6 with a relative formula (=A2 & " " & B2).      range = sheet.GetRange(COleVariant("C2"), COleVariant("C6"));      range.SetFormula(COleVariant("=A2 & \" \" & B2"));      //Fill D2:D6 with a formula(=RAND()*100000) and apply a number      //format.      range = sheet.GetRange(COleVariant("D2"), COleVariant("D6"));      range.SetFormula(COleVariant("=RAND()*100000"));      range.SetNumberFormat(COleVariant("$0.00"));      //AutoFit columns A:D.      range = sheet.GetRange(COleVariant("A1"), COleVariant("D1"));      cols = range.GetEntireColumn();      cols.AutoFit();      //Manipulate a variable number of columns for Quarterly Sales Data.      {         short NumQtrs;         CString msg;         Range resizedrange;         Interior interior;         Borders borders;         //Determine how many quarters to display data for.         for(NumQtrs=1;NumQtrs<=3;NumQtrs++)         {            msg.Format("Enter sales data for %d quarter(s)?", NumQtrs);            if(AfxMessageBox(msg,MB_YESNO)==IDYES)            {               break;            }         }         msg.Format("Displaying data for %d quarters.", NumQtrs);         AfxMessageBox(msg);         //Starting at E1, fill headers for the number of columns selected.         range = sheet.GetRange(COleVariant("E1"), COleVariant("E1"));         resizedrange = range.GetResize(covOptional, COleVariant(NumQtrs));         resizedrange.SetFormula(                COleVariant("=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\""));         //Change the Orientation and WrapText properties for the headers.         resizedrange.SetOrientation(COleVariant((short)38));         resizedrange.SetWrapText(covTrue);         //Fill the interior color of the headers.         interior = resizedrange.GetInterior();         interior.SetColorIndex(COleVariant((short)36));         //Fill the columns with a formula and apply a number format.         range = sheet.GetRange(COleVariant("E2"), COleVariant("E6"));         resizedrange = range.GetResize(covOptional, COleVariant(NumQtrs));         resizedrange.SetFormula(COleVariant("=RAND()*100"));         resizedrange.SetNumberFormat(COleVariant("$0.00"));         //Apply borders to the Sales data and headers.         range = sheet.GetRange(COleVariant("E1"), COleVariant("E6"));         resizedrange= range.GetResize(covOptional, COleVariant(NumQtrs));         borders = resizedrange.GetBorders();         borders.SetWeight(COleVariant((short)2));   //xlThin = 2         //Add a Totals formula for the Quarterly sales data and apply a         //border.         range = sheet.GetRange(COleVariant("E8"), COleVariant("E8"));         resizedrange = range.GetResize(covOptional, COleVariant(NumQtrs));         resizedrange.SetFormula(COleVariant("=SUM(E2:E6)"));         borders = resizedrange.GetBorders();         {            Border bottomborder;            bottomborder = borders.GetItem((long)9);            bottomborder.SetLineStyle(                           COleVariant((short)-4119));   //xlDouble = -4119            bottomborder.SetWeight(                           COleVariant((short)4));       //xlThick = 4         }      }      //Make the application visible and give the user control of      //Microsoft Excel.      app.SetVisible(TRUE);      app.SetUserControl(TRUE);					
  4. 将以下函数添加到 AutoProjectDLG.cpp 中,并将其放在 CAutoProjectDlg::OnRun() 前面的某个位置:

    示例代码

          void FillSafeArray(OLECHAR FAR* sz, int iRow, int iCol,                         COleSafeArray* sa)      {         VARIANT v;         long index[2];         index[0] = iRow;         index[1] = iCol;         VariantInit(&v);         v.vt = VT_BSTR;         v.bstrVal = SysAllocString(sz);         sa->PutElement(index, v.bstrVal);         SysFreeString(v.bstrVal);         VariantClear(&v);      }					
  5. 在 Developer Studio 中,运行该应用程序。出现对话框时(该示例创建了一个基于对话框的应用程序),请单击“运行”按钮。
Excel 8 8.0 XL97 XL8
属性

文章 ID:179706 - 上次审阅时间:09/18/2011 12:37:00 - 修订版本: 3.0

  • Microsoft Excel 2000 标准版
  • Microsoft Visual C++ 5.0 企业版
  • Microsoft Visual C++ 5.0 专业版
  • Microsoft Foundation Class Library 4.2
  • Microsoft Office XP Developer Edition
  • Microsoft Office 2000 Developer Edition
  • Microsoft Excel 2002 标准版
  • Microsoft Excel 97 标准版
  • kbnewfile kbfunctions kbprogramming kbautomation kbhowto kbinterop KB179706
反馈