Qt读excel获取exel数据

Qt提供了com对象操作的类QAxObject,可以通过该类读写execel数据,例如下图的excel:
Qt读excel获取exel数据

下面是Qt读excel并打印内容的代码:

#include "widget.h"
#include "ui_widget.h"
#include <QAxObject>
#include <QFileDialog>
#include <QStandardPaths>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    QAxObject *excel = new QAxObject(this);
    excel->setControl("Excel.Application");
    excel->setProperty("Visible", false);    //显示窗体看效果,选择ture将会看到excel表格被打开
    excel->setProperty("DisplayAlerts", true);
    QAxObject *workbooks = excel->querySubObject("WorkBooks");   //获取工作簿(excel文件)集合

    QString str = QFileDialog::getOpenFileName(this,"打开",
                                               QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
                                               "Excel 文件(*.xls *.xlsx)");

    //打开刚才选定的excel
    workbooks->dynamicCall("Open(const QString&)", str);
    QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
    QAxObject *worksheet = workbook->querySubObject("WorkSheets(int)",1);
    QAxObject *usedRange = worksheet->querySubObject("UsedRange");   //获取表格中的数据范围

    QVariant var = usedRange->dynamicCall("Value");  //将所有的数据读取刀QVariant容器中保存
    QList<QList<QVariant>> excel_list;  //用于将QVariant转换为Qlist的二维数组
    QVariantList varRows=var.toList();
    if(varRows.isEmpty())
    {
         return;
    }

    const int row_count = varRows.size();
    QVariantList rowData;
    for(int i=0;i<row_count;++i)
    {
        rowData = varRows[i].toList();
        excel_list.push_back(rowData);
    }

    //打印excel数据
    for(int i = 0; i<row_count; i++)
    {
        QList<QVariant> curList = excel_list.at(i);
        int curRowCount = curList.size();
        for(int j = 0; j < curRowCount; j++)
        {
            qDebug() << curList.at(j).toString();
        }
    }

    workbook->dynamicCall( "Close(Boolean)", false );
    excel->dynamicCall( "Quit(void)" );
    delete excel;
}

Widget::~Widget()
{
    delete ui;
}

输出结果

"序号"
"英雄名称"
"属性"
"伤害"
"等级"
"1"
"鲁班七号"
"射手"
"100"
"国服"
"2"
"武则天"
"法师"
"80"
"国服"
"3"
"孙悟空"
"刺客"
"105"
"省级"
"4"
"李白"
"刺客"
"90"
"村级"
"5"
"牛魔"
"辅助"
"30"
"国服"
"6"
"吕布"
"战士"
"95"
"省级"

使用说明
Qt读excel获取exel数据

上一篇:短视频源码,每日任务通过刮卡的方式选择


下一篇:golang开发GUI桌面应用fyne(五)- 计算器