I read excel file using QAxBase
and QAxObject
.
I got global variable QAxObject* db_workbook;
where I store pointer to some workbook(don't know why it called like that, but whatever) in excel. I need it because of throught it I need to get excel file data in few functions, not just only one.
When readExcelFile
method executes fine, in test_function()
an exception
appears at this line sheet_N = db_workbook->querySubObject("Worksheets(int)", 1);
Why does it happens and how to fix it?
Code part is here
//
QAxObject* db_workbook;
//for read what we need to
void importdb_module::readExcelFile(QAxObject* excel, QString& file_path){
if(initExcel(excel)){
QAxObject* workbooks = excel->querySubObject("WorkBooks");
workbooks->dynamicCall("Open (const QString&)", file_path);
QAxObject* workbook = excel->querySubObject("ActiveWorkBook");
db_workbook = workbook;//global ptr points same adress now
QAxObject* worksheets = workbook->querySubObject("WorkSheets");
//test getting sheet num 1 name
QAxObject* sheet_hh = workbook->querySubObject("Worksheets(int)", 1);
QString sheet_name = sheet_hh->property("Name").toString();
qDebug()<<sheet_name<<"TEST!";//here everything works fine
}
}
void importdb_module::test_function(){
QAxObject* sheet_N;
//ERROR IS HERE!
sheet_N = db_workbook->querySubObject("Worksheets(int)", 1);
QString sheet_name = sheet_N->property("Name").toString();
qDebug()<<sheet_name;
}
//executes on button click
void importdb_module::testExlOp(QString &_path){
QAxObject* excel;
QStringList spreadsheet_list; //get spreadsheet list when opening file
QString path = _path;//gonna use GUI choose
if(initExcel(excel)){
if (readExcelFile(excel, path)){
//
test_function();
excel->dynamicCall("Quit(void)");
}else{
//error output
QMessageBox::information(0, "", "Error");
}
}
delete excel;
}
Thank you!
Probably you have a dangling pointer. Use QPointer<QAxObject>
instead of a naked pointer. It will reset itself to null when the instance of QAxObject
gets destructed.
Generally speaking, in this day and age, you're not supposed to be using naked pointers for anything that's not implicitly owned by something else. This means that for QObjects
that have parents you don't need to do use smart pointers (although it doesn't hurt any). Generally speaking, smart pointers don't hurt. Use them.