vc6 通过ole读取excel

 参考代码如下:

	_Application m_oExcelApp;
         _Worksheet        m_oWorkSheet;     // 工作表
	_Workbook         m_oWorkBook;      // 工作簿
	Workbooks         m_oWorkBooks;    // 工作簿集合
	Worksheets        m_oWorkSheets;    // 工作表集合
          Range             m_oCurrRange;      // 使用区域
	if (!m_oExcelApp.CreateDispatch( _T( "Excel.Application" ), NULL ) ) 
	{
		::MessageBox( NULL, _T( "创建Excel服务失败!" ), _T( "错误提示!" ), MB_OK | MB_ICONERROR); 
		exit(1); 
	}

	//设置为显示
	m_oExcelApp.SetVisible(FALSE);
	m_oWorkBooks.AttachDispatch( m_oExcelApp.GetWorkbooks(), TRUE ); //没有这条语句,下面打开文件返回失败。
	
	LPDISPATCH lpDisp = NULL;
	COleVariant covTrue((short)TRUE);
    COleVariant covFalse((short)FALSE);
    COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); 
    Range       oCurCell;
	
	
	// 打开文件
	lpDisp = m_oWorkBooks.Open( _T("e:\\language_kron"),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing),
		_variant_t(vtMissing) );
	
	
	// 获得活动的WorkBook( 工作簿 )
	m_oWorkBook.AttachDispatch( lpDisp, TRUE );
	// 获得活动的WorkSheet( 工作表 )
	m_oWorkSheet.AttachDispatch( m_oWorkBook.GetActiveSheet(), TRUE );
	// 获得使用的区域Range( 区域 )
	m_oCurrRange.AttachDispatch( m_oWorkSheet.GetUsedRange(), TRUE );
	
	// 获得使用的行数
	long lgUsedRowNum = 0;
	m_oCurrRange.AttachDispatch( m_oCurrRange.GetRows(), TRUE );
	lgUsedRowNum = m_oCurrRange.GetCount();
	// 获得使用的列数
	long lgUsedColumnNum = 0;
	m_oCurrRange.AttachDispatch( m_oCurrRange.GetColumns(), TRUE );
	lgUsedColumnNum = m_oCurrRange.GetCount();
	// 读取Sheet的名称
	CString strSheetName = m_oWorkSheet.GetName();
	
	//得到全部Cells,此时,CurrRange是cells的集合 
	m_oCurrRange.AttachDispatch( m_oWorkSheet.GetCells(), TRUE ); 
	
	CString 
	
	// 遍历整个Excel表格
	//CStringArray* arrayStr;
	   CString origTxt,transTxt,szHash;
	   origTxt=_T("");
       transTxt=_T("");
	   int nItem=0;//for select string1 or string2 
	   
	   //arrayStr = new CStringArray[lgUsedRowNum];
	   for ( int i = 1; i < lgUsedRowNum; i++ )
       {
		   CString strItemName1,strItemName2,strItemName3;
		   for ( int j = 1; j < lgUsedColumnNum+1; )
		   {
			   oCurCell.AttachDispatch( m_oCurrRange.GetItem( COleVariant( (long)(i + 1)), COleVariant( (long)j ) ).pdispVal, TRUE );
			   VARIANT varItemName = oCurCell.GetText();
			   
			   if(j==1)
			   {
				   strItemName1 = varItemName.bstrVal;
			   }			   
			   
			   if(j==2)
			   {
				   
				   strItemName2 = varItemName.bstrVal;
				   
			   }
		
			   j++;
		   }
		   
	   }
	
相关文章
相关标签/搜索