Http://www.cppblog.com/wrhwww/archive/2012/03/02/129421.html#166994
First, we need to understand that VC accesses an Excel table through ODBC. That is to say, VC processes an Excel table as a database. Of course, you can also read files separated by the tab key to process such files. However, I am more willing to access the Excel table by reading the database.
Second, since it is a database, you need to create a DSN corresponding to the database. In addition, before creating a DSN, you must first confirm that the Excel driver has been installed.
Third, to access a table in the database, open the table first. In this way, A recordset corresponding to the table is required. The following code is available:
Void crwexcel: readfromexcel ()
{
Cdatabase database;
Cstring ssql;
Cstring sitem1, sitem2;
Cstring sdriver;
Cstring sdsn;
Cstring sfile = "demo.xls"; // name of the Excel file to be read
// Retrieve whether the Excel driver "Microsoft Excel Driver (*. xls)" is installed )"
Sdriver = getexceldriver ();
If (sdriver. isempty ())
{
// No Excel driver found
Afxmessagebox ("No Excel driver is installed! ");
Return;
}
// Create a string for access
Sdsn. Format ("ODBC; driver = {% s}; DSN = '''; DBQ = % s", sdriver, sfile );
Try
{
// Open the database and create the database corresponding to the Excel file
Database. Open (null, false, false, sdsn );
Crecordset recset (& database );
// Set the query sentence .demo.xls to be read in Excel instead of a file name.
Ssql = "select age, name from demo. xls ";
// Execute the query statement to open the table
Recset. Open (crecordset: forwardonly, ssql, crecordset: readonly );
// Obtain the query result
While (! Recset. iseof ())
{
// Read the internal value of Excel
Recset. getfieldvalue ("name", sitem1 );
Recset. getfieldvalue ("Age", sitem2 );
// Move to the next row
Recset. movenext ();
}
// Close the database
Database. Close ();
}
Catch (cdbexception, E)
{
// When an exception occurs during database operations...
Afxmessagebox ("Database Error:" + E-> m_strerror );
}
End_catch;
}
Note that we need to process the Excel worksheet. We need to first select the data we want to read, and then select Insert> Name>, in the input box, enter the name of the table we used in the SELECT statement. Second, you need to set the column name to the data in the first row of the selected part.