VC读写EXCEL文件类(已安装excel) - VC学习之路 - CSDN博客 下载本文

&result, pXlApp, L\ pXlBooks = result.pdispVal; }

CString strName; //Excel表完整路径

CString strTmp; //临时变量,保存单元格数据中的CString型

double dblTmp; //临时变量,保存单元格数据中的double型

//用来保存信息的数组 VARIANT arr;

arr.vt = VT_ARRAY | VT_VARIANT; SAFEARRAYBOUND sab[2];

sab[0].lLbound = 1; sab[0].cElements = row; sab[1].lLbound = 1; sab[1].cElements = col; arr.parray = SafeArrayCreate(VT_VARIANT, 2, sab); int tableNum=0; int nCount=1;

strName=strfilename;

// 调用Workbooks.Open()方法,打开一个已经存在的Workbook

IDispatch *pXlBook;

{

VARIANT parm; parm.vt = VT_BSTR;

// parm.bstrVal = ::SysAllocString(L\ parm.bstrVal=strName.AllocSysString(); VARIANT result; VariantInit(&result);

AutoWrap(DISPATCH_PROPERTYGET, &result, pXlBooks, L\ pXlBook = result.pdispVal; }

// 从Application.ActiveSheet属性获得Worksheet对象 IDispatch *pXlSheet; {

VARIANT result; VariantInit(&result);

AutoWrap(DISPATCH_PROPERTYGET, &result, pXlApp, L\ pXlSheet = result.pdispVal; }

CString strRange;

strRange=sBeginCell+_T(\

TCHAR* cRange=strRange.GetBuffer(); // 选择一个16x40大小的Range IDispatch *pXlRange; {

VARIANT parm; parm.vt = VT_BSTR;

parm.bstrVal = ::SysAllocString(cRange); VARIANT result; VariantInit(&result);

AutoWrap(DISPATCH_PROPERTYGET, &result, pXlSheet, L\ VariantClear(&parm); pXlRange = result.pdispVal; }

// 用这个Range读取数据

AutoWrap(DISPATCH_PROPERTYGET, &arr, pXlRange, L\ for(i=0; i<row; i++) {

for(j=0; j<col; j++) {

VARIANT tmp;

//tmp.vt = VT_BSTR; // 添加数据到数组中 long indices[] = {i+1,j+1};

SafeArrayGetElement(arr.parray, indices, (void *)&tmp);

strTmp=_T(\

if(tmp.vt ==VT_BSTR) {

strTmp=tmp.bstrVal; }

else if(tmp.vt==VT_R8) {

dblTmp=tmp.dblVal;

//strTmp.Format(_T(\ //dblTmp=123;

char buffer[_CVTBUFSIZE]; _gcvt( dblTmp, 16, buffer );

if((dblTmp-(int)dblTmp)==0 && strlen(buffer)>1)

buffer[strlen(buffer)-1]=buffer[strlen(buffer)]; int i=0;