// 建立XLS数据连接
BOOL CExportToExcel::CreateXlsConnection(const CString& strPath, _ConnectionPtr& ipConnection)
{
if (strPath.IsEmpty())
{
SendAnErrorMessage(_T("路径为空"));
return FALSE;
}
ipConnection = NULL;
try
{
::CoInitialize(NULL);
CString strConn = _T("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=");
strConn += strPath;
strConn += _T(";Extended Properties = \"Excel 5.0;HDR = Yes;IMEX=0\";Persist Security Info=false");
BSTR bstrConnectionString = strConn.AllocSysString();
HRESULT hr = m_ipXlsConnection.CreateInstance("ADODB.Connection");
if (FAILED(hr))
{
return FALSE;
}
hr = ipConnection->Open(bstrConnectionString, "", "", adModeUnknown);
if (FAILED(hr))
{
return FALSE;
}
_bstr_t bstrCreateSql = "CREATE TABLE TESTTABLE(ID INT, USER_NAME varchar(20))";
ipConnection->Execute(bstrCreateSql, NULL, adCmdText);
ipConnection->Close();
::CoUninitialize();
}
catch (...)
{
return FALSE;
}
return TRUE;
}
本文介绍了一种使用C++创建Excel文件数据连接的方法,并详细展示了如何通过编程方式利用OLE DB来建立与Excel文件的连接,包括初始化COM环境、设置连接字符串、创建连接对象等关键步骤。
1581

被折叠的 条评论
为什么被折叠?



