_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,adOpenKeyset
adLockOptimistic,
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() 移動到第一條記錄。
ado excel讀取
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.