CDatabase database;
CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)"; // Excel安装驱动
CString sExcelFile = fileName;//"c:\\demo.xls"; // 要建立的Excel文件
CString sSql;
TRY
{
// 创建进行存取的字符串
sSql.Format("DRIVER={%s};DSN=‘‘;FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",sDriver, sExcelFile, sExcelFile);
// 创建数据库 (既Excel表格文件)
if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
{
// 创建表结构(姓名、年龄)
sSql = "CREATE TABLE demo (Name TEXT,Age NUMBER)";
database.ExecuteSQL(sSql);
// 插入数值
sSql = "INSERT INTO demo (Name,Age) VALUES (‘徐景周‘,26)";
database.ExecuteSQL(sSql);
sSql = "INSERT INTO demo (Name,Age) VALUES (‘徐志慧‘,22)";
database.ExecuteSQL(sSql);
sSql = "INSERT INTO demo (Name,Age) VALUES (‘郭徽‘,27)";
database.ExecuteSQL(sSql);
sSql = "CREATE TABLE demo1 (Name TEXT,Age NUMBER,Sex TEXT)";
database.ExecuteSQL(sSql);
// 插入数值
sSql = "INSERT INTO demo1 (Name,Age,Sex) VALUES (‘徐景周‘,26,‘男‘)";
database.ExecuteSQL(sSql);
sSql = "INSERT INTO demo1 (Name,Age,Sex) VALUES (‘徐志慧‘,22,‘男‘)";
database.ExecuteSQL(sSql);
sSql = "INSERT INTO demo1 (Name,Age,Sex) VALUES (‘郭徽‘,27,‘女‘)";
database.ExecuteSQL(sSql);
}
// 关闭数据库
database.Close();
}
CATCH_ALL(e)
{
TRACE1("Excel驱动没有安装: %s",sDriver);
}
END_CATCH_ALL;
//通过ODBC往excel数据库中写入数据
TRY
{
// 创建进行存取的字符串
sSql.Format("DRIVER={%s};DSN=‘‘;FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",sDriver, sExcelFile, sExcelFile);
if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
{
sSql = "select * from demo";
CRecordset recordSet(&database);
recordSet.Open(CRecordset::forwardOnly, sSql);
CString strValue1, strValue2;
while (!recordSet.IsEOF())
{
//读取Excel内部数值
recordSet.GetFieldValue("Name", strValue1);
recordSet.GetFieldValue("Age", strValue2);
}
}
}
CATCH_ALL(e)
{
TRACE1("Excel驱动没有安装: %s",sDriver);
}
END_CATCH_ALL;