OLE方法打开Excel的问题
我想用OLE的方法打开一个Excel文件,并读到StringGrid里面,如果Excel数据量小的话没什么问题,数据量一大就会报错,大家先看下我的代码对不对……
- C/C++ code
void __fastcall TReadExcelForm::ExcelOpenClick(TObject *Sender){ Variant ex,wk,sht; //init try{ ex=CreateOleObject("Excel.Application"); }catch(...){ ShowMessage("无法启动Excel,可能尚未安装或文件已经损坏!"); return; } //open Excel File if(OpenExcelDialog->Execute()){ ex.OlePropertyGet("WorkBooks").OleFunction("Open",WideString(OpenExcelDialog->FileName)); wk=ex.OlePropertyGet("ActiveWorkBook"); sht=ex.OlePropertyGet("ActiveSheet"); iCol = sht.OlePropertyGet("UsedRange").OlePropertyGet("Columns").OlePropertyGet("Count"); iRow = sht.OlePropertyGet("UsedRange").OlePropertyGet("Rows").OlePropertyGet("Count"); StringGrid->ColCount = iCol+2; StringGrid->RowCount = iRow+2; for(int i=1;i<iRow;i++){ StringGrid->Cells[0][i-1] = i-1; for(int j=1;j<iCol;j++){ StringGrid->Cells[j][i-1] = sht.OlePropertyGet("Cells",i,j).OlePropertyGet("Value"); } } //Quit wk.OleProcedure("Save"); wk.OleProcedure("Close"); ex.OleFunction("Quit"); ex = Unassigned; wk = Unassigned; sht = Unassigned; }}
以上代码,出现得错误是:First chance exception at $773442EB. Exception class EVariantTypeCastError with message 'Could not convert variant of type (Error) into type (OleStr)'. Process Project1.exe (5900)
还有一点,这样退出的话还是会留下一个Excel进程,多运行几次程序,任务管理器里一排的Excel进程……有啥办法不?
请大家帮忙看看,谢谢了。
[解决办法]
不错啊,ole的代码写得这么清爽。
依照提示信息,似乎不是代码的问题。而是Excel文件的问题。可能有某些cell无法转换为string格式。
可以在那里加一个try catch.定位到指定的cell。看看格式有什么问题。
excel进程驻留的问题似乎是微软的一个bug.
[解决办法]
每次运行都有一个Excel 进程,可能是因为每次都出错了 ,没有运行到
wk.OleProcedure("Save");
wk.OleProcedure("Close");
ex.OleFunction("Quit");
ex = Unassigned;
wk = Unassigned;
sht = Unassigned;
[解决办法]
应该是在CreateOleObject成功以后,将读写Excel的代码放到try中,在__finally中退出Excel并释放相应资源。如果仅仅是在catch中才释放资源,如果代码执行成功,是不会执行catch段的内容。