在编写qt activex excel读/写代码时,如果未安装excel,请防止应用程序崩溃

时间:2016-12-19 13:27:15

标签: excel qt activex qaxobject

我使用Qt activex(QAxObject)来读取/写入excel文件。

QAxObject* excel = new QAxObject( "Excel.Application", 0 );
QAxObject* workbooks = excel->querySubObject( "Workbooks" );
QAxObject* workBook = workbooks->querySubObject("Open(const QString&)", path);
QAxObject* sheets = workBook->querySubObject( "Worksheets" );
QAxObject* sheet1 = sheets->querySubObject( "Item( int )", 1 );
QAxObject* sheet2 = sheets->querySubObject( "Item( int )", 2 );
//....

我们知道这种机制本身使用excel,并且不能在未安装excel的计算机上运行。

如果代码在这样的计算机上运行(没有安装excel),则程序崩溃。如何在代码中检测到PC上没有安装excel?

1 个答案:

答案 0 :(得分:4)

检查工作簿是否为NULL指针。根据经验,您可能希望在使用之前检查excel是否为空指针。

QAxObject* excel = new QAxObject( "Excel.Application", 0 );

if ( excel )
{
     QAxObject* workbooks = excel->querySubObject( "Workbooks" );

     if ( workbooks )
     {
           QAxObject* workBook = workbooks->querySubObject("Open(const QString&)", path);
           QAxObject* sheets = workBook->querySubObject( "Worksheets" );
           QAxObject* sheet1 = sheets->querySubObject( "Item( int )", 1 );
           QAxObject* sheet2 = sheets->querySubObject( "Item( int )", 2 );

           ...