QT 导出excel 表格

void queryOneObject(QAxObject *worksheet,QString label,int row,QString data){

    QAxObject *cellOne;

    label.append(QString::number(row));

    cellOne = worksheet->querySubObject("Range(QVariant, QVariant)",label);

    cellOne->dynamicCall("SetValue(const QVariant&)",QVariant(data));

}

void  saveout(){

//获取保存路径

    QString filepath=QFileDialog::getSaveFileName(this,tr("Save"),".",tr(" (*.xlsx)"));

    if(filepath.isEmpty()){

        ui->label_Tip->hide();

        qDebug()<<"创建exel文件失败!";

        return;

    }else{

        ui->label_Tip->show();

    }

    QVector exlData;

    exlData = actionDone::getInstance()->mSaveoutExl;

    int rows = exlData.size();

    qDebug()<<"待导出:"<

    if(rows==0){

        QMessageBox::information(nullptr,"提示",start+"--"+end+"无导出记录  ");

        return;

    }

    QAxObject *excel = new QAxObject(this);

    //连接Excel控件

    excel->setControl("Excel.Application");

    //不显示窗体

    excel->dynamicCall("SetVisible (bool Visible)","false");

    //不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改,是否保存”的提示

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

    //获取工作簿集合

    QAxObject *workbooks = excel->querySubObject("WorkBooks");

    //新建一个工作簿

    workbooks->dynamicCall("Add");

    //获取当前工作簿

    QAxObject *workbook = excel->querySubObject("ActiveWorkBook");

    //获取工作表集合

    QAxObject *worksheets = workbook->querySubObject("Sheets");

    //获取工作表集合的工作表1,即sheet1

    QAxObject *worksheet = worksheets->querySubObject("Item(int)",1);

    //设置标题

    int cellrow=1;

    queryOneObject(worksheet,"A",cellrow,"姓名");

    queryOneObject(worksheet,"B",cellrow,"年龄");

    queryOneObject(worksheet,"C",cellrow,"号码");

    queryOneObject(worksheet,"D",cellrow,"出生地");

    queryOneObject(worksheet,"E",cellrow,"爱好");

    queryOneObject(worksheet,"F",cellrow,"情况");

    QStringList Actionlist = mySet::getInstance()->mActionlist;

    QStringList statelist;

    statelist<<"未发起"<<"失败"<<"成功";

    //设置表格数据

    for(int i=0;i

        stOneContent one= exlData.at(i);

        if(isaddexcel(one)==false){

            continue;

        }

        cellrow++;

        //设置要操作的单元格,如A1,A2,A3,A4

        queryOneObject(worksheet,"A",cellrow, one.tNumber);

        queryOneObject(worksheet,"B",cellrow, one.tName);

        queryOneObject(worksheet,"C",cellrow, one.tContent);

        queryOneObject(worksheet,"D",cellrow, Actionlist[one.tAction]);

        queryOneObject(worksheet,"E",cellrow, one.tReplyWords);

        queryOneObject(worksheet,"F",cellrow, statelist[one.tzhongCai]);

    }

    //保存至filepath,用QDir::toNativeSeparators将路径中的"/"转换为"\",

    workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filepath));

    workbook->dynamicCall("Close()");

    excel->dynamicCall("Quit()");//关闭excel

    delete excel;

    excel= nullptr;

    qDebug() << "\n导出成功";

    ui->label_Tip->hide();

    QMessageBox::information(nullptr,"提示", "导出完成");

}

你可能感兴趣的:(QT 导出excel 表格)