分类: WINDOWS
//名称:OnReadexcel
//功能:从Excel文件中读取相应数据并显示出来
//作者:徐景周( jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.1
/////////////////////////////////////////////////////////////////////////////
void CRWExcelDlg::OnReadexcel()
{
CDatabase database;
CString sSql;
CString sItem1, sItem2;
CString sDriver;
CString sDsn;
CString sFile,sPath;
//获取主程序所在路径,存在sPath中
GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer ();
int nPos;
nPos=sPath.ReverseFind ('\\');
sPath=sPath.Left (nPos);
sDriver = GetExcelDriver();//作者自己写的函数
if (sDriver.IsEmpty())
{
// 没有发现Excel驱动
AfxMessageBox("没有安装Excel驱动!");
return;
}
// 创建进行存取的字符串
sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s", sDriver, sFile);
{
// 打开数据库(既Excel文件)
database.Open(NULL, false, false, sDsn);
CRecordset recset(&database);
sSql = "SELECT Name, Age "
"FROM Exceldemo " ;
"ORDER BY Name ";
// 执行查询语句
recset.Open(CRecordset::forwardOnly, sSql, CRecordset::readOnly);
while (!recset.IsEOF())
{
//读取Excel内部数值
recset.GetFieldValue("Name", sItem1);
recset.GetFieldValue("Age", sItem2);
m_ExcelList.AddString( sItem1 + " --> "+sItem2 );
recset.MoveNext();
}
database.Close();
}
CATCH(CDBException, e)
{
// 数据库操作产生异常时...
AfxMessageBox("数据库错误: " + e->m_strError);
}
END_CATCH;
}
//名称:GetExcelDriver
//功能:获取ODBC中Excel驱动
//作者:徐景周( jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.1
/////////////////////////////////////////////////////////////////////////////
CString CRWExcelDlg::GetExcelDriver()
{
char szBuf[2001];
WORD cbBufMax = 2000;
WORD cbBufOut;
char *pszBuf = szBuf;
CString sDriver;
if (!SQLGetInstalledDrivers(szBuf, cbBufMax, &cbBufOut))
return "";
do
{ //检索已安装的驱动是否有Excel,如果没有则先在ODBC中添加一个名为"Excel"的项
if (strstr(pszBuf, "Excel") != 0)//
{
//发现 !
sDriver = CString(pszBuf);
break;
}
pszBuf = strchr(pszBuf, '\0') + 1;
}
while (pszBuf[1] != '\0');
}
//名称:OnWriteexcel
//功能:创建并写入数据到Excel文件中
//作者:徐景周( jingzhou_xu@163.net)
//组织:未来工作室(Future Studio)
//日期:2002.9.1
/////////////////////////////////////////////////////////////////////////////
void CRWExcelDlg::OnWriteexcel() //此函数是通过CRWExcelDlg对话框类中的一个按钮调用
{
CDatabase database;
CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)"; // Excel安装驱动
CString sExcelFile,sPath;
CString sSql;
//获取主程序所在路径,存在sPath中
GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer ();
int nPos;
nPos=sPath.ReverseFind ('\\');
sPath=sPath.Left (nPos);
{
// 创建进行存取的字符串
sSql.Format("DRIVER={%s};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",sDriver, sExcelFile, sExcelFile);
if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
{
// 创建表结构(姓名、年龄)
sSql = "CREATE TABLE Exceldemo (Name TEXT,Age NUMBER)";
database.ExecuteSQL(sSql);
sSql = "INSERT INTO Exceldemo (Name,Age) VALUES ('徐景周',26)";
database.ExecuteSQL(sSql);
database.ExecuteSQL(sSql);
database.ExecuteSQL(sSql);
}
database.Close();
}
CATCH_ALL(e)
{
TRACE1("Excel驱动没有安装: %s",sDriver);
}
END_CATCH_ALL;
}
1416



被折叠的 条评论
为什么被折叠?



