QWidget中含有QComboBox和QSpinBox,将数据保存到Excel中(上)

tech2022-09-16  96

QWidget中含有QComboBox和QSpinBox,将数据保存到Excel中

 

先看效果

在看代码

void NumView::on_saveFileBtn_clicked() { QString fileName = QFileDialog::getSaveFileName(this,tr("Excle file"),QString("./test.xls"),tr("Excel Files(*.xls)")); //设置保存的文件名 if(fileName != NULL) { QAxObject *excel = new QAxObject; if(excel->setControl("Excel.Application")) { excel->dynamicCall("SetVisible (bool Visible)",false); excel->setProperty("DisplayAlerts",false); QAxObject *workbooks = excel->querySubObject("WorkBooks"); //获取工作簿集合 workbooks->dynamicCall("Add"); //新建一个工作簿 QAxObject *workbook = excel->querySubObject("ActiveWorkBook"); //获取当前工作簿 QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1); QAxObject *cell; int rowCount = ui->tableWidget->rowCount(); int columnCount = ui->tableWidget->columnCount(); /*添加Excel表头数据*/ for(int i = 1; i <= columnCount ; i++) { cell = worksheet->querySubObject("Cells(int,int)", 1, i); cell->setProperty("RowHeight", 40); cell->dynamicCall("SetValue(const QString&)", ui->tableWidget->horizontalHeaderItem(i-1)->data(0).toString()); } /*将form列表中的数据依此保存到Excel文件中*/ for(int j = 2; j <= rowCount + 1;j++) { for(int k = 1;k <= 6 ;k++)//ui->tableWidget->columnCount(); { cell = worksheet->querySubObject("Cells(int,int)", j, k); if(k == 2) cell->dynamicCall("SetValue(const QString&)", m_stepComboBox[j-2]->currentText()+"\t"); else if(k == 3) cell->dynamicCall("SetValue(const QString&)", m_limitComboBox[j-2]->currentText() +"\t"); else if(k == 4) cell->dynamicCall("SetValue(const QString&)", QString::number(m_volgate[j-2]->value()) + "\t"); else if(k == 5) cell->dynamicCall("SetValue(const QString&)", QString::number(m_current[j-2]->value()) + "\t"); else if(k == 6) cell->dynamicCall("SetValue(const QString&)", QString::number(m_timeItem[j-2]->value()) + "\t"); else cell->dynamicCall("SetValue(const QString&)",ui->tableWidget->item(j-2,k-1)->text()+ "\t"); } } /*将生成的Excel文件保存到指定目录下*/ workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName)); //保存至fileName workbook->dynamicCall("Close()"); //关闭工作簿 excel->dynamicCall("Quit()"); //关闭excel delete excel; excel = NULL; if (QMessageBox::question(NULL,QString::fromUtf8("完成"), QString::fromUtf8("文件已经导出,是否现在打开?"), QMessageBox::Yes|QMessageBox::No) ==QMessageBox::Yes) { QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName))); } } } }

参考了一些大佬的代码,在这里感谢

最新回复(0)