Create an Excel Database using MFC ODBC

Submitted by Date of submission User level 

Mahesh Chand Dec 01, 2000 Beginner 

#include  and  

CDatabase MFC ODBC class can be used to create an excel database. I have used SQL queries to create a database table and INSERT..INTO query to add data to the table. My database name is "c:\\temp\\ExclDB1.xls". I have create a table in this database called 'MyTableA' with three fields Name, Address and SSN in it. You can modify this code according to your needs.

CDatabase m_db;;

// This is your excel sheet name. I will use it as my excel database in my next article.

CString szExcelDBName = "c:\\temp\\ExclDB1.xls"; 

CString sSql;

try

{

// Build the creation string for access without DSN

sSql.Format("DRIVER={MICROSOFT EXCEL DRIVER (*.XLS)};DSN='';READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s", szExcelDBName, szExcelDBName);

// Create the database (i.e. Excel sheet)

if( m_db.OpenEx(sSql, CDatabase::noOdbcDialog) )

{

// Create table structure

sSql = "CREATE TABLE myTableA (Name VARCHAR(50), Address VARCHAR(255), SSN LONG )";

m_db.ExecuteSQL(sSql);

// Add data to the table

m_db.ExecuteSQL("INSERT INTO myTableA (Name, Address, SSN ) VALUES ('Mahesh', 'Programming Village, Philadelphia', 23123243 )" );

m_db.ExecuteSQL("INSERT INTO myTableA (Name, Address, SSN ) VALUES ('Joe', 'Pittsburgh', 34534 )");

m_db.ExecuteSQL("INSERT INTO myTableA (Name, Address, SSN ) VALUES ('Amanda', 'Downingtown', 3874534 )");

// Close the database

if ( m_db.IsOpen() )

m_db.Close();

}

catch( CException* e )

{

e->ReportError();

}

 

Required: #include  and  in stdafx.h of your project.