Qt 读取excel

Posted 积跬步,到千里

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt 读取excel相关的知识,希望对你有一定的参考价值。

void CMainWindow::openExcel(QString fileName)
{
    QAxObject excel("Excel.Application");
    excel.setProperty("Visible", false);
    QAxObject *work_books = excel.querySubObject("WorkBooks");
    work_books->dynamicCall("Open(const QString&)", fileName);

    QAxObject *work_book = excel.querySubObject("ActiveWorkBook");
    QAxObject *work_sheets = work_book->querySubObject("Sheets");  //Sheets也可换用WorkSheets

    int sheet_count = work_sheets->property("Count").toInt();  //获取工作表数目
    if (sheet_count > 0)
    {
        QAxObject *work_sheet = work_book->querySubObject("Sheets(int)", 1);

        ui.label->setText("文件数据读取中...");
        QVariant var = readAll(work_sheet);
        castVariant2ListListVariant(var);
    }

    work_book->dynamicCall("Close(Boolean)", false);  //关闭文件
    excel.dynamicCall("Quit(void)");  //退出
}

QVariant CMainWindow::readAll(QAxObject *sheet)
{
    QVariant var;
    if (sheet != NULL && !sheet->isNull())
    {
        QAxObject *usedRange = sheet->querySubObject("UsedRange");
        if (NULL == usedRange || usedRange->isNull())
        {
            return var;
        }
        var = usedRange->dynamicCall("Value");
        delete usedRange;
    }
    return var;
}

void CMainWindow::castVariant2ListListVariant(const QVariant &var)
{
    QVariantList varRows = var.toList();
    if (varRows.isEmpty())
    {
        return;
    }
    const int rowCount = varRows.size();
    QVariantList rowData;
    for (int i = 0; i < rowCount; ++i)
    {
        rowData = varRows[i].toList();

        if (i == 0)
        {
            QStringList headers;
            for each (auto item in rowData)
            {
                QString value = item.toString();
                headers.append(value);
            }
            ui.tableWidget->setColumnCount(headers.size()); //设置列数
            ui.tableWidget->setHorizontalHeaderLabels(headers);
        }
        else
        {
            int row = ui.tableWidget->rowCount();
            ui.tableWidget->setRowCount(row + 1);
            for (int j = 0; j < rowData.size(); j++)
            {
                QString value = rowData[j].toString();
                QTableWidgetItem *item = new QTableWidgetItem(value);
                ui.tableWidget->setItem(row, j, item);
            }
        }
    }
}

 

以上是关于Qt 读取excel的主要内容,如果未能解决你的问题,请参考以下文章

Qt 读取excel

qt 或 C++ 可以在没有安装 office excel 或其他必备框架的情况下读取 excel

QT快速读取Excel

用qt读写excel文件一定要安装excel么

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

2021-04-15qt对xlsx文件的读取