To read and write Excel table files directly through ODBC, first, make sure that you have a driver for Excel table files installed in ODBC, MICROSOFT Excel DRIVER (*. XLS) ". You can then proceed according to the following steps:
1. In the StdAfx.h document, add:
#include <afxdb.h>
#include <odbcinst.h>
2. Create an Excel file directly through ODBC and insert data into the table (tentative file name: Demo.xls)
Create and write Excel files
void Crwexcel::writetoexcel ()
{
CDatabase database;
CString sdriver = "MICROSOFT EXCEL DRIVER (*. XLS) "; Excel installation Driver
CString sexcelfile = "C:\\demo.xls"; The Excel file to build
CString sSQL;
TRY
{
Creating a string for access
Ssql.format ("driver={%s};D sn="; Firstrowhasnames=1; Readonly=false; Create_db=\ "%s\";D bq=%s ",
Sdriver, Sexcelfile, sexcelfile);
Create a database (both Excel table files)
if (database. OpenEx (Ssql,cdatabase::noodbcdialog))
{
Create a table structure (name, age)
sSQL = "CREATE TABLE demo (Name text,age number)";
Database. ExecuteSQL (sSQL);
Insert numeric value
sSQL = "INSERT into demo (name,age) VALUES (' Xu Jingzhou ', 26)";
Database. ExecuteSQL (sSQL);
sSQL = "INSERT into demo (name,age) VALUES (' Xuzhihui ', 22)";
Database. ExecuteSQL (sSQL);
sSQL = "INSERT into demo (name,age) VALUES (' Guo Hui ', 27)";
Database. ExecuteSQL (sSQL);
}
Close Database
Database. Close ();
}
Catch_all (e)
{
TRACE1 ("Excel driver not installed:%s", sdriver);
}
End_catch_all;
}