MFC中使用ado方式读取excel表格的内容由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“mfc读取excel数据”。
在MFC中利用ADO的方式连接excel表格,和连接acce数据库很相似,只不过在一些连接语句上有细微的差别,但是就是由于这些差别,可能就是怎么样都连接不了.1.在stdaxf.h中加入对ado的支持,即: #import“C:Program FilesCommon FilesSystemadomsado15.dll” no_namespace rename(“EOF”,“adoEOF”)2.建立连接对象:_ConnectionPtr m_pConnection 并初始化m_pConnection.CreateInstance(__uuidof(Connection));连接语句:(我的操作环境是VC++和win7)
“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:副本1月14日总装车间扭矩检测表.xls;Extended Properties=”Excel 8.0;HDR=No;IMEX=1“” 其中“IMEX=1”若是你的excel表格比较复杂,比如一列中既有文本又有公式数字,那就一定要加上它,加上它以后在读取excel表格数据时不会改变内容,全部按文本格式读取,要不然会出现读文本读不了数字和读数字读不了文本的情况 m_pConnectionExcel.CreateInstance(__uuidof(Connection));CString strCon;// CString m_fn=_T(“E: ext.xls”);strCon.Format(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E: ext.xls;Extended Properties=”Excel 8.0;HDR=No;IMEX=1“”);try {
m_pConnectionExcel->Open((_bstr_t)strCon,“”,“”,adModeUnknown);} catch(_com_error e){
CString strError;
strError.Format(“警告:打开链接发生异常。错误消息:%s”,e.ErrorMeage());
AfxMeageBox(strError);}
3.然后就是就是建立指针集和读取数据了: _RecordsetPtr m_pRecordsetExcel;CString strSQL=_T(“”);strSQL.Format(_T(“select * from [sheet1$]”));m_pRecordsetExcel.CreateInstance(__uuidof(Recordset));try {
m_pRecordsetExcel->Open((_bstr_t)strSQL.AllocSysString(),(_variant_t)m_pConnectionExcel.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);}
catch(_com_error e){
CString strError;
strError.Format(“警告:打开数据表时发生异常。错误消息:%s”,e.ErrorMeage());
AfxMeageBox(strError);} 4.然后就可以读取数据了,例如下面的代码是读取F列(A列对应0)第1行的内容,并显示出来 _variant_t var1 = m_pRecordsetExcel->GetFields()->GetItem((long)6)->Value;
CString strName1;
if(var1.vt!= VT_NULL)
strName1 =(LPCSTR)_bstr_t(var1);
MeageBox(strName1);可以通过m_pRecordsetExcel->MoveNext();语句继续往下读。