qt tablewidget导出为excel代码
时间: 2023-08-28 16:08:08 浏览: 108
QT中用QTableWdiget导出Excel表格
以下是使用Qt中的QTableWidget导出为Excel的示例代码:
```cpp
void MainWindow::on_exportButton_clicked()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Excel"), "", tr("Excel Files (*.xls)"));
if (fileName != "") {
QTableWidget *table = ui->tableWidget;
QFile file(fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
QTextStream stream(&file);
stream << "sep=,\n";
for (int i = 0; i < table->columnCount(); i++) {
QTableWidgetItem *item = table->horizontalHeaderItem(i);
if (item) {
stream << item->text() << ",";
}
}
stream << "\n";
for (int i = 0; i < table->rowCount(); i++) {
for (int j = 0; j < table->columnCount(); j++) {
QTableWidgetItem *item = table->item(i, j);
if (item) {
stream << item->text() << ",";
} else {
stream << ",";
}
}
stream << "\n";
}
file.close();
QMessageBox::information(this, tr("Export Successful"), tr("The table was successfully exported as an Excel file."));
}
}
}
```
这个函数使用了QFileDialog来让用户选择保存Excel文件的位置,然后在文件中写入表头和表格数据。在表头和表格数据之间使用了逗号分隔符,以便在Excel中正确地解析数据。最后,它会显示一个消息框,告诉用户导出成功。
阅读全文