Qt中一个奇怪的excel读取错误

A strange reading excel error with Qt

本文关键字:excel 读取 取错误 一个 Qt      更新时间:2023-10-16

在我的项目中,我试图阅读excel文件。然而,奇怪的事情发生了。当我打开excel可见,它将正确执行。当我把它设置为不可见时,它不会打开我的文件。

Qt版本:Qt -opensource-windows-x86-msvc2015_64-5.7.0

Windows版本:64位win-10

控制台错误信息:

QAxBase: Error calling IDispatch member Open: Unknown Error

读取Excel文件的代码:
QAxObject *excel = NULL;
QAxObject *workbooks = NULL;
QAxObject *workbook = NULL;
excel = new QAxObject("Excel.Application");
excel->dynamicCall("SetVisible(bool)", false);
    // The code to set invisible, project will work correctly when set visible true
workbooks = excel->querySubObject("WorkBooks");
if(!workbooks){
    QMessageBox msgBox;
            msgBox.setWindowTitle("error information");
            msgBox.setText("workbooks error");
            msgBox.exec();
    return;
}
workbook = workbooks->querySubObject("Open(const QString&, QVariant)", file->filePath, 0);
    //This code will not execute correctly, causing "workbook error"
if(!workbook){
    QMessageBox msgBox;
            msgBox.setWindowTitle("error information");
            msgBox.setText("workbook error");
            msgBox.exec();
    return;
}
QAxObject * worksheet = workbook->querySubObject("WorkSheets(int)", 1);
QAxObject * usedrange = worksheet->querySubObject("UsedRange");
QAxObject * rows = usedrange->querySubObject("Rows");
QAxObject * columns = usedrange->querySubObject("Columns");
int intRowStart = usedrange->property("Row").toInt();
int intColStart = usedrange->property("Column").toInt();
int intCols = columns->property("Count").toInt();
int intRows = rows->property("Count").toInt();
workbook->dynamicCall("Close (Boolean)", false);
delete excel;

try this:

workbooks->querySubObject("Open(const QString&)",QString(path));

我遇到同样的情况,当它不可见时,我试着这样做:

excel->setProperty("EnableEvents",false);

qt-version:4.8.6 windows -version:10 excel:2013

明白了!我认为这是Excel服务的错误。

Just change your code :
excel->dynamicCall("SetVisible(bool)", **true**); 
And add another: 
excel->dynamicCall("SetVisible(bool)", **false**),
after workbooks = excel->querySubObject("WorkBooks");
work on Qt5.6 excel 2013;

我不知道原因,但它有一点飞溅。