第一:下載QXlsx庫文件
https://download.csdn.net/download/qq_32663053/90739425
第二:在Qt項目中引入QXlsx庫,需要把QXlsx庫文件放在項目文件夾下
第三:將tableview中的數據存入到excl文件
代碼:
void MainWindow::saveTableViewToExcel(QTableView *tableView,QString title) {
// 創建Excel文檔
QXlsx::Document xlsx;
// 獲取數據模型
QXlsx::Format format,format1;
format.setTextWrap(true); // 設置文本自動換行
format.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
format.setVerticalAlignment(QXlsx::Format::AlignVCenter);
format1.setTextWrap(true); // 設置文本自動換行
format1.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
format1.setVerticalAlignment(QXlsx::Format::AlignVCenter);
format1.setFontSize(20);
QString filePath = QFileDialog::getSaveFileName(this, tr("Save File"),"",tr("Excel Files (*.xlsx *.xls)"));
// 遍歷模型數據,寫入Excel
QAbstractItemModel *model = tableView->model();
int length=model->columnCount();
char last='A'+length-1;
QString last1=QString(QChar(last));
xlsx.mergeCells("A1:"+last1+"1");
xlsx.write(1, 1, title,format1);
for(int i=0;i<model->columnCount();i++){
xlsx.setColumnWidth(i+1,25);
xlsx.write(2, i+1, model->headerData(i, Qt::Horizontal).toString(),format);
}
for (int row = 2; row < model->rowCount()+2; row++) {
for (int col = 0; col < model->columnCount(); col++) {
QModelIndex index = model->index(row-2, col);
xlsx.write(row + 1, col + 1, model->data(index).toString(),format);
}
}
// 保存Excel文件
xlsx.saveAs(filePath);
if(filePath!="")
QMessageBox::information(this,"提示","數據導出完畢");
//delete xlsx
}
保存到指定文件。
第四:將Excl數據讀取到Qt應用程序
程序:
QString filePath = "E:/1.xlsx";
// 創建QXlsx::Document對象并加載文件
QXlsx::Document xlsx(filePath);
// 檢查文件是否成功加載
if (xlsx.isLoadPackage()) {
int sheetCount = xlsx.workbook()->sheetCount();
for (int sheetIndex = 0; sheetIndex < sheetCount; ++sheetIndex) {
QXlsx::Worksheet *sheet = dynamic_cast<QXlsx::Worksheet*>(xlsx.workbook()->sheet(sheetIndex));
if (sheet) {
int rowCount = sheet->dimension().lastRow();
int columnCount = sheet->dimension().lastColumn();
for (int row = 1; row <= rowCount; ++row) {
for (int column = 1; column <= columnCount; ++column) {
QXlsx::Cell *cell = sheet->cellAt(row, column);
if (cell) {
QString value = cell->value().toString();
qDebug() << "Sheet" << sheetIndex << "Cell(" << row << "," << column << "):" << value;
}
}
}
}
}
} else {
qDebug() << "文件加載失敗";
}
以上是簡單的通過QXlsx庫文件,對Excl文件進行導入和導出。