QT之Excel表格操作

QT之Excel表格操作

  • 提前准备
  • 打开读取excel文件
  • 写入保存excel文件

提前准备

pro文件中添加:
QT += axcontainer
在需要使用excel的文件中添加:
#include
#include

打开读取excel文件

    QAxObject *excel = NULL;    //本例中,excel设定为Excel文件的操作对象
    QAxObject *workbooks = NULL;
    QAxObject *workbook = NULL;  //Excel操作对象
    int column_count;
    QStringList data;
    QString dbname;
    QString sql_date;

    excel = new QAxObject("Excel.Application");
    excel->dynamicCall("SetVisible(bool)", false); //true 表示操作文件时可见,false表示为不可见
    excel->setProperty("EnableEvents",false);
    workbooks = excel->querySubObject("WorkBooks");

    QString nums = QFileDialog::getOpenFileName(this,tr("选择文件"),"./",tr("*.xls *.xlsx"));
    if(nums.isEmpty())
    {
        return;
    }
    QFile *file = new QFile;
    file->setFileName(nums);
    if(file->open(QIODevice::ReadOnly))
    {
        workbook = workbooks->querySubObject("Open(QString&)", nums);
        // 获取打开的excel文件中所有的工作sheet
        workbook = excel->querySubObject("ActiveWorkBook");  //获取工作簿
        QAxObject * worksheets = workbook->querySubObject("WorkSheets");
        int iWorkSheet = worksheets->property("Count").toInt();  //获取工作表的数目

        //qDebug() << QString("Excel文件中表的个数: %1").arg(QString::number(iWorkSheet));
        QAxObject* pWorkSheet = workbook->querySubObject("Sheets(int)", 1);//获取第一张表
        QAxObject* used_range = pWorkSheet->querySubObject("UsedRange"); //获取该sheet的使用范围对象
        QVariant var = used_range->dynamicCall("Value");

        QAxObject *rows  = used_range->querySubObject("Rows");
        QAxObject *columns = used_range->querySubObject("Columns");

        int row_start = used_range->property("Row").toInt();          //获得开始行
        int column_start  = used_range->property("Column").toInt();     //获得开始列
        int row_count = rows->property("Count").toInt();
        column_count = columns->property("Count").toInt();

        delete used_range;
        QVariantList varRows = var.toList();            //得到表格中的所有数据
        if(varRows.isEmpty()){return;}
        const int rowCount = varRows.size();
        qDebug()<<"总行数:"<<row_count;
        qDebug()<<"总列数:"<<column_count;
        for(int i = 0;i<rowCount-1;i++)      
        {
            QVariantList rowData = varRows[i].toList();
            qDebug()<<"数据:"<<i<<rowData[4].toString();  
        }

        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");       //断开连接,接收新的连接
        file->close();                      //关闭文件
    }
    else
    {
        qDebug()<<"没有文件";
    }
    workbook->dynamicCall("Close (Boolean)", false);  //关闭文件
    delete excel;               //回收指针
    excel = NULL;

写入保存excel文件

你可能感兴趣的:(QT基本操作,excel,qt5)