ado excel读取

来源:互联网 发布:淘宝u站 编辑:程序博客网 时间:2024/05/18 01:06
_ConnectionPtr pConnection;_RecordsetPtr pRecordset;CString tableName;pConnection.CreateInstance("ADODB.Connection");//两种初始化只能ADO只能指针的方式pRecordset.CreateInstance (__uuidof(Recordset));CString adoinfo;//m_PathName是Excel文件的全路径adoinfo.Format(_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Extended Properties=Excel 8.0"),m_PathName);//连接Excel2003,其它版本连接串不一样try                 {  pConnection->Open((_bstr_t)adoinfo,"","",adModeUnknown);//读取表名pRecordset = NULL;pRecordset = pConnection->OpenSchema(adSchemaTables);_bstr_t table_name;CStringArray table_array;while(!pRecordset->adoEOF)//获得表名{table_name = pRecordset->Fields->GetItem("TABLE_NAME")->Value;tableName=(LPCSTR)table_name;pRecordset->MoveNext();table_array.Add(tableName);}for(int inTable=0;inTable<table_array.GetSize();inTable++)//循环查询工作表,选择出储存数据的工作薄{pRecordset->Close();pRecordset.Release();pRecordset=NULL;pRecordset.CreateInstance (__uuidof(Recordset));//每次Release连接对象以后,都要重新初始化连接对象。CString strSQL;strSQL.Format("SELECT * FROM [%s]",table_array.GetAt(inTable));try{pRecordset->Open(_bstr_t(strSQL),                // 查询DemoTable表中所有字段pConnection.GetInterfacePtr(), // 获取库接库的IDispatch指针adOpenForwardOnly,//adOpenDynamic,adOpenKeysetadLockOptimistic,adCmdText);}catch(_com_error e){EndWaitCursor(); AfxMessageBox(e.Description()); return false;}//到这里就获取了一个Excel文件中一个表的所有数据的记录。//pRecordset->GetFields()->GetCount ();获取表中的字段数//获取序号为index的字段名//b_FieldName=pRecordset->GetFields()->GetItem(_variant_t(long(index)))->GetName()//获取指定当前记录指定字段(井名)的值//pRecordset->GetFields()->GetItem(_variant_t("井名"))->Value//pRecordset->MoveNext();移动到下条记录//pRecordset->MoveFirst() 移动到第一条记录。

原创粉丝点击