QTabelView和QTabelWidget匯出Excel三種方法
阿新 • • 發佈:2018-12-12
感謝以下博主的部落格
話不多說,直接上程式碼:
方法一:
QString filepath = QFileDialog::getSaveFileName(this, tr("Save as..."), QString(), tr("EXCEL files (*.xls *.xlsx)")); int row = m_model->rowCount(); int col = m_model->columnCount(); QList<QString> list; //新增列標題 QString HeaderRow; for (int i = 0; i<col; i++) { HeaderRow.append(m_model->horizontalHeaderItem(i)->text() + "\t"); } list.push_back(HeaderRow); for (int i = 0; i<row; i++) { QString rowStr = ""; for (int j = 0; j<col; j++) { rowStr += m_model->item(i, j)->text() + "\t"; } list.push_back(rowStr); } QTextEdit textEdit; for (int i = 0; i<list.size(); i++) { textEdit.append(list.at(i)); } QFile file(filepath); if (file.open(QFile::WriteOnly | QIODevice::Text)) { QTextStream ts(&file); ts.setCodec("UTF-8"); ts << textEdit.document()->toPlainText(); file.close(); }
方法二:(只加資料)
QString filePath = QFileDialog::getSaveFileName(this, "Save Data", "untitle", "Microsoft Excel 2013(*.xlsx)"); if (!filePath.isEmpty()) { QAxObject *excel = new QAxObject(this); 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 *worksheets = workbook->querySubObject("Sheets"); QAxObject *worksheet = worksheets->querySubObject("Item(int)", 1); int rowCount = m_model->rowCount(); int columnCount = m_model->columnCount(); for (int i = 1; i < rowCount+1; ++i) { for (int j = 1; j < columnCount+1; ++j) { QAxObject *Range = worksheet->querySubObject("Cells(int,int)", i, j); Range->dynamicCall("SetValue(const QString &)", m_model->item(i-1, j-1)->text()); } } workbook->dynamicCall("SaveAs(const QString &)", QDir::toNativeSeparators(filePath)); if (excel != NULL) { excel->dynamicCall("Quit()"); delete excel; excel = NULL; } QMessageBox::information(this, QStringLiteral("提示"), "Exporting data successful"); }
方法三:(完整版)
QString fileName = QFileDialog::getSaveFileName(this, QStringLiteral("儲存"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), QStringLiteral("Excel 檔案(*.xls *.xlsx)")); if (fileName != "") { QAxObject *excel = new QAxObject; if (excel->setControl("Excel.Application")) //連線Excel控制元件 { excel->dynamicCall("SetVisible (bool Visible)", "false");//不顯示窗體 excel->setProperty("DisplayAlerts", false);//不顯示任何警告資訊。如果為true那麼在關閉是會出現類似“檔案已修改,是否儲存”的提示 QAxObject *workbooks = excel->querySubObject("WorkBooks");//獲取工作簿集合 workbooks->dynamicCall("Add");//新建一個工作簿 QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//獲取當前工作簿 QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1); int i, j; int colount = m_model->columnCount(); int rowcount = m_model->rowCount(); QAxObject *cell, *col; //標題行 cell = worksheet->querySubObject("Cells(int,int)", 1, 1); cell->dynamicCall("SetValue(const QString&)", QStringLiteral("系統日誌")); cell->querySubObject("Font")->setProperty("Size", 18); //調整行高 worksheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30); //合併標題行 QString cellTitle; cellTitle.append("A1:"); cellTitle.append(QChar(colount - 1 + 'A')); cellTitle.append(QString::number(1)); QAxObject *range = worksheet->querySubObject("Range(const QString&)", cellTitle); range->setProperty("WrapText", true); range->setProperty("MergeCells", true); range->setProperty("HorizontalAlignment", -4108);//xlCenter range->setProperty("VerticalAlignment", -4108);//xlCenter //列標題 for (i = 0; i<colount; i++) { QString columnName; columnName.append(QChar(i + 'A')); columnName.append(":"); columnName.append(QChar(i + 'A')); col = worksheet->querySubObject("Columns(const QString&)", columnName); col->setProperty("ColumnWidth", m_tableview->columnWidth(i) / 6); cell = worksheet->querySubObject("Cells(int,int)", 2, i + 1); //QTableView 獲取表格頭部文字資訊 columnName= m_model->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString(); cell->dynamicCall("SetValue(const QString&)", columnName); cell->querySubObject("Font")->setProperty("Bold", true); cell->querySubObject("Interior")->setProperty("Color", QColor(191, 191, 191)); cell->setProperty("HorizontalAlignment", -4108);//xlCenter cell->setProperty("VerticalAlignment", -4108);//xlCenter } //資料區 //QTableView 獲取表格資料部分 for(i=0;i<rowcount;i++) //行數 { for (j=0;j<colount;j++) //列數 { QModelIndex index = m_model->index(i, j); QString strdata= m_model->data(index).toString(); worksheet->querySubObject("Cells(int,int)", i+3, j+1)->dynamicCall("SetValue(const QString&)", strdata); } } //畫框線 QString lrange; lrange.append("A2:"); lrange.append(colount - 1 + 'A'); lrange.append(QString::number(m_model->rowCount() + 2)); range = worksheet->querySubObject("Range(const QString&)", lrange); range->querySubObject("Borders")->setProperty("LineStyle", QString::number(1)); range->querySubObject("Borders")->setProperty("Color", QColor(0, 0, 0)); //調整資料區行高 QString rowsName; rowsName.append("2:"); rowsName.append(QString::number(m_model->rowCount() + 2)); range = worksheet->querySubObject("Range(const QString&)", rowsName); range->setProperty("RowHeight", 20); workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(fileName));//儲存至fileName workbook->dynamicCall("Close()");//關閉工作簿 excel->dynamicCall("Quit()");//關閉excel delete excel; excel = NULL; if (QMessageBox::question(this, QStringLiteral("完成"), QStringLiteral("檔案已經匯出,是否現在開啟?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { QDesktopServices::openUrl(QUrl("file:///" + QDir::toNativeSeparators(fileName))); } } else { QMessageBox::warning(NULL, QStringLiteral("錯誤"), QStringLiteral("未能建立 Excel 物件,請安裝 Microsoft Excel。"), QMessageBox::Apply); } }
效果圖: