对于一个Excel文件,我用CDatabase::Open()可以打开,
可是怎样才能知道这个文件里有几个表(sheet),以及这些表的名字?
以便我用CRecordset::Open()打开呢?简单点说:就是怎样得到Excel中的表谢谢各位
可是怎样才能知道这个文件里有几个表(sheet),以及这些表的名字?
以便我用CRecordset::Open()打开呢?简单点说:就是怎样得到Excel中的表谢谢各位
调试欢乐多
可是怎样才能知道这个文件里有几个表(sheet),以及这些表的名字?????
以便我用CRecordset::Open()打开呢????????
************************************如果我知道表名,自然可以打开(用Excel查看当然不算)简单点说:就是怎样得到Excel中的表的名字现在我才体会什么是:好心不一定能办好事
先得到数据源表的个数据iSumTable;
再得到第index索引表的名字 index >= 0 && index < iSumTable
具体函数见MSDN最好创建一个CStringArray类的对象,将所有表的名字都存入到里面,随用随取!
#include <stdio.h>
#include <windows.h>
#include <comdef.h>
#import "c:\program files\common files\system\ado\msado20.tlb" no_namespace rename ("EOF", "adoEOF")
HRESULT hr;
int main()
{
hr=CoInitialize(NULL);
_ConnectionPtr m_pConnection;
_CommandPtr m_commandptr;
_RecordsetPtr m_pUserSet;
try
{
//使用odbc的连接字符串
// _bstr_t conn("DRIVER={Microsoft Excel Driver (*.xls)};DriverId=790;DBQ=E:\\temp.xls;DefaultDir=e:\\;");
//使用ole db的连接字符串
_bstr_t conn("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\\temp.xls;Extended Properties=""Excel 8.0;""" );
m_pConnection.CreateInstance (__uuidof(Connection));
m_pConnection->Open (conn,"","",-1);
_RecordsetPtr pRstSchema = NULL;
pRstSchema = m_pConnection->OpenSchema(adSchemaTables);
while(!(pRstSchema->adoEOF))
{
_bstr_t table_name = pRstSchema->Fields->GetItem("TABLE_NAME")->Value;
printf("Table Name: %s\n",(LPCSTR) table_name);
_bstr_t table_type = pRstSchema->Fields->GetItem("TABLE_TYPE")->Value;
printf("Table type: %s\n\n",(LPCSTR) table_type);
pRstSchema->MoveNext();
}
//比方说如果table_name为test$的话,那么sqltext中的表名应该为[test$],就是在表名前加上"[]"
//就是这个"[]"浪费了我很多时间
_bstr_t sqltext="SELECT * from [test$] ";
m_commandptr.CreateInstance (__uuidof(Command));
m_pUserSet.CreateInstance (__uuidof(Recordset));
m_commandptr->ActiveConnection =m_pConnection ;
m_commandptr->CommandText =sqltext;
m_commandptr->CommandType =adCmdText;
m_pUserSet=m_commandptr->Execute (NULL,NULL,adCmdUnknown);
_variant_t filed[12];
_bstr_t filedname[12];
bool befirstrow=true;
while (!m_pUserSet->adoEOF )
{
long kk=m_pUserSet->GetFields ()->GetCount ();
for (long uu=0;uu<kk;uu++)
{
filedname[uu]=m_pUserSet->GetFields ()->GetItem ((_variant_t)uu)->GetName ();
filed[uu]=m_pUserSet->GetCollect (filedname[uu]);
printf("%s\t ",(char*)(_bstr_t)(filed[uu]));
}
printf("\r\n");
m_pUserSet->MoveNext ();
}
}
catch(_com_error * e)
{
MessageBox(NULL,"",e->ErrorMessage(),MB_OK);
}
catch(...)
{
long errorcount=m_pConnection->GetErrors ()->GetCount ();
char add[255];
strcpy(add,"");
for (short i=0;i<errorcount;i++)
{
strcat(add,m_pConnection->GetErrors ()->GetItem (_variant_t((short)i))->GetDescription ());
}
printf(add);
}
CoUninitialize();
return 0;
}