代码如下:
(pro文件中添加QT += axcontainer)
#include <QAxObject>void MainWindow::saveTableToExcel() {QDateTime current_date_time =QDateTime::currentDateTime();QString excelName = "data_" + current_date_time.toString("yyyy-MM-dd_hh-mm-ss");QString filePath = QFileDialog::getSaveFileName(this, "Save Data", excelName, "Microsoft Excel 2013(*.xlsx)");int row = ui->originDataTable->rowCount();int col = ui->originDataTable->columnCount();QAxObject* excel = new QAxObject(this);//excel->setControl("ket.Application");//wpsexcel->setControl("Excel.Application"); //Excelexcel->dynamicCall("SetVisible(bool Visible)", false);excel->setProperty("DisplayAlerts", false);QAxObject* workbooks = excel->querySubObject("WorkBooks");workbooks->dynamicCall("Add");QAxObject* workbook = excel->querySubObject("ActiveWorkBook");QAxObject* worksheets = workbook->querySubObject("Sheets");QAxObject* worksheet = worksheets->querySubObject("Item(int)", 1);for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {QAxObject* Range = worksheet->querySubObject("Cells(int,int)", i + 1, j + 1);Range->dynamicCall("SetValue(const QString &)", ui->originDataTable->item(i, j)->text());}}workbook->dynamicCall("SaveAs(const QString &)", QDir::toNativeSeparators(filePath));if (excel != NULL) {excel->dynamicCall("Quit()");delete excel;excel = NULL;}QMessageBox::information(this, QStringLiteral("提示"), "保存成功");
}