Step 1: add an included file
# Include "excel9.h" // use the header file to be included in the Excel class
# Include "comdef. H" // use the header file to be included in the Excel class
(Note: "excel9.h" and "excel9.cpp" are required. You can download them online. If not, contact me)
Step 2: Create an object
_ Application excelapp;
Workbooks wbsmybooks;
_ Workbook wbmybook;
Worksheets wssmysheets;
_ Worksheet wsmysheet;
Range rgmyrge;
Step 3: Create an Excel Server
/* Create an Excel server */
If (! Excelapp. createdispatch ("Excel. Application", null ))
{
Afxmessagebox ("An error occurred while creating the Excel server! ");
Return;
}
Step 4: Use an Excel template to create an Excel document
// Strpath is the full path name of the template.
Wbsmybooks. attachdispatch (excelapp. getworkbooks (), true );
Try
{
Wbmybook. attachdispatch (wbsmybooks. Add (_ variant_t (strpath )));
}
Catch (...)
{
Afxmessagebox ("An error occurred while opening the Excel template. Check whether the file exists! ", Mb_ OK | mb_iconstop );
Excelapp. Quit ();
Return;
}
Step 5: Associate objects
/* Get worksheets */
Wssmysheets. attachdispatch (wbmybook. getworksheets (), true );
/* Get worksheet1 */
Wsmysheet. attachdispatch (wssmysheets. getitem (_ variant_t ("sheet1"), true );
/* Obtain all cells. rgmyrge is the set of cells */
Rgmyrge. attachdispatch (wsmysheet. getcells (), true );
Step 6: Set the cell value
Rgmyrge. setitem (_ variant_t (long) 1), _ variant_t (long) 1), _ variant_t ("name"); // 1*1
Rgmyrge. setitem (_ variant_t (long) 1), _ variant_t (long) 2), _ variant_t ("QQ"); // 1*2
Rgmyrge. setitem (_ variant_t (long) 2), _ variant_t (long) 1), _ variant_t (""); rgmyrge. setitem (_ variant_t (long) 2), _ variant_t (long) 2), _ variant_t ("278800584 "));
Step 7: Print and preview
Excelapp. setvisible (true );
Wbmybook. printpreview (_ variant_t (false ));
Step 8: exit the Excel applicationProgram
/* Set the Save flag to saved. The save template dialog box is not displayed,
Actually it is not saved, but it is thought that the flag is saved, because it does not need to be saved here */
Wbmybook. setsaved (true );
/* Exit the Excel application */
Excelapp. Quit ();
Step 9: release an object
/* Release the object */
Rgmyrge. releasedispatch ();
Wsmysheet. releasedispatch ();
Wssmysheets. releasedispatch ();
Wbmybook. releasedispatch ();
Wbsmybooks. releasedispatch ();
Excelapp. releasedispatch ();