您的位置:首页 > 其它

运用ADO访问Excel,并对其进行操作

2015-03-16 15:12 176 查看
运用ADO访问时:

第一步:

//该导出语句放在stdafx.h文件中,且放在所有#include<>后面
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")

第二步:

数据库的初始化,一般放在基于对话框的应用程序.cpp InitInstance()函数中

if (!AfxOleInit())
{
AfxMessageBox(_T("初始化失败"));
return FALSE;
}

第三步:

一些简单操作的代码:

public:
_ConnectionPtr m_pConnection;

_bstr_t strConnection=_T("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;Data Source=C:\\Documents and Settings\\Administrator\\桌面\\ExelDemo.xls;Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\"");
HRESULT hr;
try
{
hr=m_pConnection.CreateInstance(_T("ADODB.Connection"));//创建Connection对象
if (SUCCEEDED(hr))
{
hr=m_pConnection->Open(strConnection,_T(""),_T(""),adModeUnknown);//连接数据库
}
}
catch (_com_error e)
{
CString errormessage;
errormessage.Format(_T("连接数据库失败!\r\n错误信息:%s"),e.ErrorMessage());
AfxMessageBox(errormessage);
}

//读取Excel里面数据

BOOL CADODlg::ReadExcelData()
{
_RecordsetPtr rcdset=NULL;
HRESULT hr;
CStringArray tbNames;
try
{
//获取所有表单
rcdset=m_pConnection->OpenSchema(adSchemaTables);
while(!rcdset->adoEOF)
{
CString strTbName=rcdset->GetFields()->GetItem(_T("TABLE_NAME"))->Value;
if (strTbName.IsEmpty()==FALSE)
{
if (strTbName.Find('$')>0)//取表名含有$的表,以防重复
{
tbNames.Add(strTbName);
}
}
rcdset->MoveNext();
}
}
catch (_com_error e)
{
CString errormessage;
errormessage.Format(_T("读取数据失败!\r\n错误信息:%s"),e.ErrorMessage());
AfxMessageBox(errormessage);
return FALSE;
}
rcdset->Close();
//获取表单中的数据
hr=rcdset.CreateInstance(__uuidof(Recordset));
int nSheet=tbNames.GetCount();
CString strSql;
CString strData;
for (int ii=0;ii<nSheet;ii++)//循环表单
{
CString strTbName=tbNames.GetAt(ii);
strSql.Format(_T("SELECT Num,Name,Sex,Comp FROM [%s]"),strTbName);
try
{
rcdset->Open(_bstr_t(strSql),m_pConnection.GetInterfacePtr(),
adOpenDynamic,adLockOptimistic,adCmdText);
rcdset->MoveFirst();
while(!rcdset->adoEOF)
{
m_strNum=rcdset->GetCollect(_T("Num"));
m_strName=rcdset->GetCollect(_T("Name"));
m_strSex=rcdset->GetCollect(_T("Sex"));
m_strComp=rcdset->GetCollect(_T("Comp"));
strData=m_strNum+_T(" ")+m_strName+_T(" ")+m_strSex+_T(" ")+m_strComp;
m_lstData.AddString(strData);
rcdset->MoveNext();
}
}
catch (_com_error e)
{
CString strError;
strError.Format(_T("警告:打开数据表时发生异常。错误信息:%s"),e.ErrorMessage());
AfxMessageBox(strError);
return FALSE;
}
rcdset->Close();
}
return TRUE;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: