Prevent application crash when excel is not installed while writing qt activex excel read/write codes

349 Views Asked by At

I'm using Qt activex (QAxObject) in order to read/write excel files.

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 );
//....

We know that this mechanism uses excel itself and is not working on computers that excel is not installed.

If the code runs on such computers (without excel installed), then, the program crashes. How can I detect in the code that excel is not installed on PC?

1

There are 1 best solutions below

1
On BEST ANSWER

You check if workbooks is NULL pointer. As a rule of thumb, you may want to check if excel is null pointer before using it.

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 );

           ...