ADO对Excel进行写操作的问题
bool ADOConn::Initialize(CString strPath, int sheet, bool rw){
bool Isok=true;
CoInitialize(NULL); //初始化
CString strSql;
CString strSelect;
//设置初始化链接路径
strSql="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=";
strSql+=strPath;
if (rw) //rw位true时,进行读,否则进行写
strSql+=";Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\"";
else
strSql+=";Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=0\"";
//Sql语句,sheet位第几个表单
strSelect.Format(L"select * from [sheet%d$]",sheet);
_bstr_t bstrSQL=(_bstr_t)strSelect;
try
{
m_pConnection.CreateInstance(__uuidof(Connection));
//strConnect="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Try;Extended Properties=\"Excel 12.0;HDR=No;IMEX=0\"";
strConnect=strSql;
//连接
m_pConnection->Open(strConnect,"","",adModeUnknown);
m_pRecordset.CreateInstance(_uuidof(Recordset));
m_pRecordset->Open(bstrSQL,_variant_t((IDispatch*)m_pConnection,true),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch(_com_error &e) //捕捉错误信息
{
Isok=false;
AfxMessageBox(e.ErrorMessage());
}
return Isok;
}
void ADOConn::WriteData(int row, int col, CString strData)
{
try
{
//我想每次直接在excel最后一行第col个格子写东西
m_pRecordset->MoveFirst();
if (row!=1) //移动到第row行
for (int i=0; i<row; i++)
m_pRecordset->MoveNext();
m_pRecordset->AddNew();
m_pRecordset->PutCollect((_variant_t)col,(_variant_t)strData);//每次运行到这里便抛出错误
m_pRecordset->Update();
}
catch (_com_error &e)
{
AfxMessageBox(e.ErrorMessage());
}
}
求大神改进!!!还有我不要通过update的SQL语句来执行