VC ADO读取Excel单元格

来源:互联网 发布:inputdirector mac版 编辑:程序博客网 时间:2024/06/03 07:26

VC ADO读取Excel单元格  

最近要读取Excel单元格...VC也是第一次使用.留个记念吧

 

/*
Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\mypath;

SQL表达式"SELECT * FROM [sheet1$]"。例如:在excel工作表名称后面跟"$"字符并且使用"[" "]"将其括起来。  
 OLE DB 
 标准
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";

"HDR=Yes;" 表示工作表的第一行是表头,没有数据。 "HDR=No;"与之相反。
"IMEX=1;"告诉驱动程序始终将"intermixed"数据类型(numbers, dates, strings等等)作为文本型读取。
注意:该选项可能引起Excel工作表写权限的修改。

*/

//构造函数,参数为Excel完整路径
ADOReader::ADOReader(CString file)
{

 ConnectionString = _T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=");  
 ConnectionString += file;   //excel   file   name  
 ConnectionString += _T(";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"");


 BSTR resultsString = ConnectionString.AllocSysString();
 pConnection.CreateInstance(__uuidof(Connection));
 }

//析构函数,销毁连结

ADOReader::~ADOReader()
{
 if(pConnection)pConnection.Release();
}

//读取字符参数列索引,行索引

CString ADOReader::ReaderCell(int rowindex,int cellindex)
{
 CString result("");

 _RecordsetPtr pRecordset;
 pRecordset.CreateInstance(__uuidof(Recordset));
 
 BSTR resultsString = ConnectionString.AllocSysString();

 pConnection->Open(resultsString,"","",adModeUnknown);
 pRecordset->Open("select * from [TestSheet$]",
  pConnection.GetInterfacePtr(),
  adOpenDynamic,
  adLockOptimistic,
  adCmdText);

 if(pRecordset->adoEOF)return _T("该文档没有内容");
 int i = 0;

 while(!pRecordset -> adoEOF)
 {
  if(pRecordset -> adoEOF)break;
  if( i == rowindex)
  {
   if(cellindex < pRecordset->Fields->Count )
   {

    _variant_t t = _variant_t(long(cellindex));
    result = (LPCSTR)_bstr_t(pRecordset->GetCollect(t));
   }
   else
   {
    result ="列索引超出范围";
   }
  }
  i++;
  pRecordset -> MoveNext();
 }

 if( rowindex > i)result ="行索引超出范围";
  
 pRecordset->Close();
 if(pRecordset)pRecordset.Release();
 pConnection->Close();
 return result;
}

 

运行还令人满意,第一次写也存在这样或是那样的不足.欢迎大家指正

原创粉丝点击