Microsoft KB Archive/308292

= How To Automate Excel to Create And Format a New Workbook Using C++ .NET and MFC =

Article ID: 308292

Article Last Modified on 6/29/2004

-

APPLIES TO


 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition
 * Microsoft Foundation Class Library 4.2
 * Microsoft Office Excel 2003
 * Microsoft Excel 2002 Standard Edition
 * Microsoft Excel 2000 Standard Edition

-



This article was previously published under Q308292



For a Microsoft Visual Basic .NET version of this article, see 301982.

For a Microsoft Visual C# .NET version of this article, see 302084.



Note Microsoft Visual C++ .NET (2002) supports both the managed code model that is provided by the Microsoft .NET Framework and the unmanaged native Microsoft Windows code model. The information in this article applies only to unmanaged Visual C++ code.



SUMMARY
This article demonstrates how to create an Automation client for Excel by using Microsoft Foundation Classes (MFC) and Visual C++ .NET.



MORE INFORMATION
Automation is a process that allows applications that are written in languages such as MFC to programmatically control other applications. Automation to Excel allows you to perform actions such as creating a new workbook, adding data to the workbook, or creating charts. With Excel and other Microsoft Office applications, virtually all of the actions that you can perform manually through the user interface can also be performed programmatically by using Automation.

Excel exposes this programmatic functionality through an object model. The object model is a collection of classes and methods that serve as counterparts to the logical components of Excel. For example, there is an Application object, a Workbook object, and a Worksheet object, each of which contain the functionality of those pieces of Excel. To access the object model from MFC and Visual C++ .NET, you can create an MFC wrapper class from Excel's type library.

This article demonstrates how to use the wrapper classes that are generated by MFC to create and format a new workbook by using Visual C++ .NET.

Create an Automation Client for Microsoft Excel
 Follow the steps in the &quot;Create an Automation Client&quot; section of the following Microsoft Knowledge Base article to create a basic Automation client:

307473 How To Use a Type Library for Office Automation from Visual C++ .NET

In step 4d of the article, select the following interfaces:

 _Application Workbooks _Workbook Worksheets _Worksheet</li> Range</li> Font</li> Interior</li> Borders</li> Border</li></ul>

In step 6 of the article (where you add #include statements for each of the classes for which you generated wrappers), note that the file for the Font class is CFont0.h and the file for the Interior class is Cnterior.h.</li>  In the IDD_AUTOPROJECT_DIALOG dialog box, right-click Run and select Add event handler. In the Event Handler Wizard, select the BN_CLICKED message type and then click Add and Edit. Add the following code in the handler for automating Excel: void CAutoProjectDlg::OnBnClickedRun {  // Commonly used OLE variants. COleVariant covTrue((short)TRUE), covFalse((short)FALSE), covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

CApplication app; CWorkbooks books; CWorkbook book; CWorksheets sheets; CWorksheet sheet; CRange range; CFont0 font; CRange cols; CRange resizedrange; Cnterior interior; CBorders borders; CBorder bottomborder;

// Start Excel and get an Application object. if(!app.CreateDispatch(&quot;Excel.Application&quot;)) {     AfxMessageBox(&quot;Couldn't start Excel and get Application object.&quot;); return; }

//Get a new workbook. books = app.get_Workbooks; book = books.Add (covOptional);

//Get the first sheet. sheets =book.get_Sheets; sheet = sheets.get_Item(COleVariant((short)1));

//Fill cells A1, B1, C1, and D1 one cell at a time with &quot;headers&quot;. range = sheet.get_Range(COleVariant(&quot;A1&quot;),COleVariant(&quot;A1&quot;)); range.put_Value2(COleVariant(&quot;First Name&quot;)); range = sheet.get_Range(COleVariant(&quot;B1&quot;),COleVariant(&quot;B1&quot;)); range.put_Value2(COleVariant(&quot;Last Name&quot;)); range = sheet.get_Range(COleVariant(&quot;C1&quot;),COleVariant(&quot;C1&quot;)); range.put_Value2(COleVariant(&quot;Full Name&quot;)); range = sheet.get_Range(COleVariant(&quot;D1&quot;),COleVariant(&quot;D1&quot;)); range.put_Value2(COleVariant(&quot;Salary&quot;));

//Format A1:D1 as bold, vertical alignment = center. range = sheet.get_Range(COleVariant(&quot;A1&quot;), COleVariant(&quot;D1&quot;)); font = range.get_Font; font.put_Bold(covTrue); range.put_VerticalAlignment(     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&quot;John&quot;, 0, 0, &saRet); FillSafeArray(L&quot;Smith&quot;, 0, 1, &saRet); FillSafeArray(L&quot;Tom&quot;, 1, 0, &saRet); FillSafeArray(L&quot;Brown&quot;, 1, 1, &saRet); FillSafeArray(L&quot;Sue&quot;, 2, 0, &saRet); FillSafeArray(L&quot;Thomas&quot;, 2, 1, &saRet);

FillSafeArray(L&quot;Jane&quot;, 3, 0, &saRet); FillSafeArray(L&quot;Jones&quot;, 3, 1, &saRet); FillSafeArray(L&quot;Adam&quot;, 4, 0, &saRet); FillSafeArray(L&quot;Johnson&quot;, 4, 1, &saRet);

range = sheet.get_Range(COleVariant(&quot;A2&quot;), COleVariant(&quot;B6&quot;)); range.put_Value2(COleVariant(saRet));

saRet.Detach; }

//Fill C2:C6 with a relative formula (=A2 & &quot; &quot; & B2). range = sheet.get_Range(COleVariant(&quot;C2&quot;), COleVariant(&quot;C6&quot;)); range.put_Formula(COleVariant(&quot;=A2 & \&quot; \&quot; & B2&quot;));

//Fill D2:D6 with a formula(=RAND*100000) and apply a number //format. range = sheet.get_Range(COleVariant(&quot;D2&quot;), COleVariant(&quot;D6&quot;)); range.put_Formula(COleVariant(&quot;=RAND*100000&quot;)); range.put_NumberFormat(COleVariant(&quot;$0.00&quot;));

//AutoFit columns A:D. range = sheet.get_Range(COleVariant(&quot;A1&quot;), COleVariant(&quot;D1&quot;)); cols = range.get_EntireColumn; cols.AutoFit;

//Manipulate a variable number of columns for Quarterly Sales Data. {     short NumQtrs; CString msg;

//Determine how many quarters to display data for. for(NumQtrs=1;NumQtrs<=3;NumQtrs++) {        msg.Format(&quot;Enter sales data for %d quarter(s)?&quot;, NumQtrs); if(AfxMessageBox(msg,MB_YESNO)==IDYES) {           break; }     }      msg.Format(&quot;Displaying data for %d quarters.&quot;, NumQtrs); AfxMessageBox(msg);

//Starting at E1, fill headers for the number of columns selected. range = sheet.get_Range(COleVariant(&quot;E1&quot;), COleVariant(&quot;E1&quot;)); resizedrange = range.get_Resize(covOptional, COleVariant(NumQtrs)); resizedrange.put_Formula(        COleVariant(&quot;=\&quot;Q\&quot; & COLUMN-4 & CHAR(10) & \&quot;Sales\&quot;&quot;)); //Change the Orientation and WrapText properties for the headers. resizedrange.put_Orientation(COleVariant((short)38)); resizedrange.put_WrapText(covTrue); //Fill the interior color of the headers. interior = resizedrange.get_Interior; interior.put_ColorIndex(COleVariant((short)36));

//Fill the columns with a formula and apply a number format. range = sheet.get_Range(COleVariant(&quot;E2&quot;), COleVariant(&quot;E6&quot;)); resizedrange = range.get_Resize(covOptional, COleVariant(NumQtrs)); resizedrange.put_Formula(COleVariant(&quot;=RAND*100&quot;)); resizedrange.put_NumberFormat(COleVariant(&quot;$0.00&quot;));

//Apply borders to the Sales data and headers. range = sheet.get_Range(COleVariant(&quot;E1&quot;), COleVariant(&quot;E6&quot;)); resizedrange= range.get_Resize(covOptional, COleVariant(NumQtrs)); borders = resizedrange.get_Borders; borders.put_Weight(COleVariant((short)2));  //xlThin = 2

//Add a Totals formula for the Quarterly sales data and apply a     //border. range = sheet.get_Range(COleVariant(&quot;E8&quot;), COleVariant(&quot;E8&quot;)); resizedrange = range.get_Resize(covOptional, COleVariant(NumQtrs)); resizedrange.put_Formula(COleVariant(&quot;=SUM(E2:E6)&quot;)); borders = resizedrange.get_Borders; {        bottomborder = borders.get_Item((long)9); bottomborder.put_LineStyle(           COleVariant((short)-4119));   //xlDouble = -4119 bottomborder.put_Weight(           COleVariant((short)4));       //xlThick = 4 }  }

//Make the application visible and give the user control of  //Excel. app.put_Visible(TRUE); app.put_UserControl(TRUE); }                   </li>  Add the following code immediately above the OnBnClickedRun method. This code simplifies creating an array that is used to send data to Excel: 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);

}                   </li> Press F5 to build and run the Automation client.</li> When the dialog box appears, click Run.

The Automation client starts Excel and creates a sample workbook. Excel remains running even when the Automation client ends because the user has been given control of the application.</li></ol>

<div class="idea_section">

Troubleshooting
If you add class wrappers for the Excel object library by using the File option in the Add Class From TypeLib Wizard, you may receive an error message when you browse to the object library. To avoid this problem, type the full path and file name for the object library instead of browsing to the file. For additional information, click the article number below to view the article in the Microsoft Knowledge Base:

311408 BUG: 'Read-Only' Warning When Adding MFC Class From Library

If you receive the following error message when you build your sample application, change &quot;Variant DialogBox&quot; in CRange.h to &quot;Variant _DialogBox&quot;:

warning C4003: not enough actual parameters for macro 'DialogBoxA'

For more information on the cause of this error, see the following Knowledge Base article:

311407 BUG: MFC Wizard Doesn't Resolve Naming Conflicts with API Macros

<div class="references_section">