(資料圖片僅供參考)
1、如何使用COleSafeArray實現(xiàn)二維數(shù)組將字符串寫入excel// VARTYPE vt = VT_BSTR ; /*數(shù)組元素的類型,string*/ VARTYPE vt = VT_I4; /*數(shù)組元素的類型,long*/SAFEARRAYBOUND sabWrite[2]; /*用于定義數(shù)組的維數(shù)和下標(biāo)的起始值*/sabWrite[0].cElements = 1;sabWrite[0].lLbound = 0;sabWrite[1].cElements = 3;sabWrite[1].lLbound = 0;COleSafeArray olesaWrite;olesaWrite.Create(vt, sizeof(sabWrite)/sizeof(SAFEARRAYBOUND), sabWrite);/*通過指向數(shù)組的指針來對二維數(shù)組的元素進行間接賦值*/long (*pArray)[2] = NULL;olesaWrite.AccessData((void **)&pArray);memset(pArray, 0, sabWrite[0].cElements * sabWrite[1].cElements * sizeof(long));/*釋放指向數(shù)組的指針*/olesaWrite.UnaccessData();pArray = NULL;/*對二維數(shù)組的元素進行逐個賦值*/long index[2] = {0, 0};long lFirstLBound = 0;long lFirstUBound = 0;long lSecondLBound = 0;long lSecondUBound = 0;olesaWrite.GetLBound(1, &lFirstLBound);olesaWrite.GetUBound(1, &lFirstUBound);olesaWrite.GetLBound(2, &lSecondLBound);olesaWrite.GetUBound(2, &lSecondUBound);for (long i = lFirstLBound; i <= lFirstUBound; i++){index[0] = i ;for (long j = lSecondLBound; j <= lSecondUBound; j++){index[1] = j;long lElement = str[j];//CString lElement = ch;olesaWrite.PutElement(index, &lElement);}}/*把ColesaWritefeArray變量轉(zhuǎn)換為VARIANT,并寫入到Excel表格中*/VARIANT varWrite = (VARIANT)olesaWrite;range.put_Value2(varWrite);這樣能將輸入的整形寫入excel。
2、當(dāng)變成VT_BSTR報內(nèi)存不足,求指導(dǎo)如何修改------解決方案--------------------可以通過另外一種寫法,CRange write_range = start_range.get_Offset(COleVariant((long)7),COleVariant((long)j)) ; write_range.put_Value2((COleVariant)(str[j]));。
本文到此分享完畢,希望對大家有所幫助。