OLE方法打开Excel的问题

charon 2009-05-11 11:01:48
我想用OLE的方法打开一个Excel文件,并读到StringGrid里面,如果Excel数据量小的话没什么问题,数据量一大就会报错,大家先看下我的代码对不对……

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进程……有啥办法不?

请大家帮忙看看,谢谢了。
...全文
463 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ccrun.com 2009-05-13
  • 打赏
  • 举报
回复
应该是在CreateOleObject成功以后,将读写Excel的代码放到try中,在__finally中退出Excel并释放相应资源。如果仅仅是在catch中才释放资源,如果代码执行成功,是不会执行catch段的内容。
castlooo 2009-05-12
  • 打赏
  • 举报
回复

加到catch里面
try
{
.....
}
catch(Exception &e)
{
wk.OleProcedure("Close");
ex.OleFunction("Quit");
ex = Unassigned;
wk = Unassigned;
sht = Unassigned;
}
castlooo 2009-05-12
  • 打赏
  • 举报
回复
每次运行都有一个Excel 进程,可能是因为每次都出错了 ,没有运行到

wk.OleProcedure("Save");
wk.OleProcedure("Close");
ex.OleFunction("Quit");
ex = Unassigned;
wk = Unassigned;
sht = Unassigned;

castlooo 2009-05-12
  • 打赏
  • 举报
回复
Ex.OlePropertyGet("WorkBooks").OleProcedure("Open",ExcelFileName.c_str());

AnsiString sFileName = OpenExcelDialog->FileName;
ex.OlePropertyGet("WorkBooks").OleFunction("Open", sFileName.c_str());
子正 2009-05-11
  • 打赏
  • 举报
回复
不错啊,ole的代码写得这么清爽。

依照提示信息,似乎不是代码的问题。而是Excel文件的问题。可能有某些cell无法转换为string格式。
可以在那里加一个try catch.定位到指定的cell。看看格式有什么问题。

excel进程驻留的问题似乎是微软的一个bug.

1,178

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder 数据库及相关技术
社区管理员
  • 数据库及相关技术社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧