VC ADO讀取Excel單元格

 

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;
}

 

運行還令人滿意,第一次寫也存在這樣或是那樣的不足.歡迎大家指正

發佈了6 篇原創文章 · 獲贊 11 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章