The CppAutomateExcel example demonstrates how to write VC++ codes to create a Microsoft Excel instance, create a workbook, fill data into a specific range, save the workbook, close the Microsoft Excel application and then clean up unmanaged COM resources.
There are three basic ways you can write VC++ automation codes:
1. Automating Excel using the #import directive and smart pointers
The code in Solution1.h/cpp demonstrates the use of #import to automate Excel. #import (http://msdn.microsoft.com/en-us/library/8etzzkb6.aspx), a new directive that became available with Visual C++ 5.0, creates VC++ "smart pointers" from a specified type library. It is very powerful, but often not recommended because of reference-counting problems that typically occur when used with the Microsoft Office applications. Unlike the direct API approach in Solution2.h/cpp, smart pointers enable us to benefit from the type info to early/late bind the object. #import takes care of adding the messy guids to
the project and the COM APIs are encapsulated in custom classes that the #import directive generates.
2. Automating Excel using C++ and the COM APIs
The code in Solution2.h/cpp demontrates the use of C/C++ and the COM APIs to automate Excel. The raw automation is much more difficult, but it is sometimes necessary to avoid the overhead with MFC, or problems with #import. Basically, you work with such APIs as CoCreateInstance(), and COM interfaces such as IDispatch and IUnknown.
3. Automating Excel with MFC
With MFC, Visual C++ Class Wizard can generate "wrapper classes" from the type libraries. These classes simplify the use of the COM servers. Automating Excel with MFC is not covered in this sample.