Qt 将TableWidget表格数据保存到Excle详细介绍

结果图:

需要的头文件

需要根据小伙伴的数据进行变更,下面是tableWidget控件表格的数据保存到Excle

附上代码:

ui->progressBar->show();    //进度条需要在ui文件中加个progressBar控件
ui->progressBar->setValue(0);   //设置进度条的值为0
QString fileName = QFileDialog::getSaveFileName(this,tr("Excle file"),QString("./paper_list.xls"),tr("Excel Files(*.xls)"));    //设置保存的文件名
if(fileName != "")
{
ui->progressBar->setValue(10);
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;
 
/*添加Excel表头数据*/
for(int i = 1; i <= ui->tableWidget->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());
if(ui->progressBar->value()<=50)
{
ui->progressBar->setValue(10+i*5);
}
}
 
/*将form列表中的数据依此保存到Excel文件中*/
for(int j = 2; j<=ui->tableWidget->rowCount()+1;j++)
{
for(int k = 1;k<=ui->tableWidget->columnCount();k++)
{
cell=worksheet->querySubObject("Cells(int,int)", j, k);
cell->dynamicCall("SetValue(const QString&)",ui->tableWidget->item(j-2,k-1)->text()+ "	");
}
if(ui->progressBar->value()<80)
{
ui->progressBar->setValue(50+j*5);
}
}
 
/*将生成的Excel文件保存到指定目录下*/
workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName)); //保存至fileName
workbook->dynamicCall("Close()");                                                   //关闭工作簿
excel->dynamicCall("Quit()");                                                       //关闭excel
delete excel;
excel=NULL;
 
ui->progressBar->setValue(100);
if (QMessageBox::question(NULL,QString::fromUtf8("完成"),QString::fromUtf8("文件已经导出,是否现在打开?"),QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
{
QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName)));
}
ui->progressBar->setValue(0);
ui->progressBar->hide();
}
}
经验分享 程序员 微信小程序 职场和发展