Qt 读写Excel,并显示到tablewidget
时间: 2023-12-22 11:05:29 浏览: 112
QT 读取和显示excel
要在Qt中读写Excel,并显示到tablewidget,可以使用QAxObject类。下面是一个简单的示例代码:
```
QAxObject* excel = new QAxObject("Excel.Application", this);
excel->setProperty("Visible", false);
QAxObject* workbooks = excel->querySubObject("Workbooks");
QAxObject* workbook = workbooks->querySubObject("Open(const QString&)", "path/to/excel/file");
QAxObject* sheets = workbook->querySubObject("Sheets");
QAxObject* sheet = sheets->querySubObject("Item(int)", 1); // 读取第一个sheet
QAxObject* used_range = sheet->querySubObject("UsedRange");
QAxObject* rows = used_range->querySubObject("Rows");
QAxObject* columns = used_range->querySubObject("Columns");
int row_count = rows->property("Count").toInt();
int column_count = columns->property("Count").toInt();
QTableWidget* table = new QTableWidget(row_count, column_count, this);
for (int row = 1; row <= row_count; ++row) {
for (int column = 1; column <= column_count; ++column) {
QAxObject* cell = sheet->querySubObject("Cells(int,int)", row, column);
QString value = cell->property("Value").toString();
table->setItem(row - 1, column - 1, new QTableWidgetItem(value));
cell->clear();
delete cell;
}
}
used_range->clear();
delete used_range;
delete sheet;
delete sheets;
delete workbook;
delete workbooks;
delete excel;
```
这段代码首先创建一个Excel对象,并打开指定的Excel文件。然后,它读取文件中的第一个sheet,并将其数据显示在QTableWidget中。注意,在读取单元格的值后,我们需要清除QAxObject对象并删除它,以避免内存泄漏。
阅读全文