1. In view-classwizad-autometion, click Add class-from a Type Library and select execl. EXE (office2003 ).
2. Select "_ application/_ workbook/_ worksheet/range/workbooks/worksheets" from the list. Click "OK" and add "Excel. cpp" and "Excel. H" to the project directory.
3. In one of you. Add Excel-related variables to the H file or define them directly in the function:
_ Application excelapp; // variables required for Excell table operations
Workbooks wbsmybooks;
_ Workbook wbmybook;
Worksheets wssmysheets;
_ Worksheet wsmysheet;
Range myrange;
4. Add the following code for clicking an event for a button:
Void cexceltestdlg: onok ()
{
Couninitialize ();
If (coinitialize (null )! = 0)
{
Afxmessagebox ("failed to initialize com support library! ");
}
// Start Excell
If (! Excelapp. createdispatch ("Excel. Application", null ))
{
Afxmessagebox ("An error occurred while creating the Excell service! ");
Exit (1 );
}
Excelapp. setvisible (false );
// Create a new document using the template file
Cstring strpath;
Cstring strpath1;
Getcurrentdirectory (max_path, strpath. getbuffer (max_path); // get the current path
Strpath1.format ("% S // 11.xls", strpath); // name of the Excel table to be operated
Wbsmybooks. attachdispatch (excelapp. getworkbooks (), true );
Wbmybook. attachdispatch (wbsmybooks. Add (_ variant_t (strpath1 )));
Wssmysheets. attachdispatch (wbmybook. getworksheets (), true );
Wsmysheet. attachdispatch (wssmysheets. getitem (_ variant_t ("sheet1"), true );
Myrange. attachdispatch (wsmysheet. getcells (), true );
Int ROW = 2;
Cstring smsg;
Exceltostring (row, 1, smsg); // read data from column 1 of row to smsg
Cdialog: onok ();
}
Void cexceltestdlg: exceltostring (INT row, int Col, cstring & smsg)
{
Variant vmsg;
Char cmsg [512];
Vmsg = myrange. getitem (_ variant_t (long) row), _ variant_t (long) COL ));
_ Bstr_t bmsg = (_ bstr_t) vmsg;
Strcpy (cmsg, BMSG );
Smsg = cmsg;
}
I forgot to mention it yesterday. The _ variant_t type must contain the following header file for identification:
# Include <comdef. h>