qt如何用QAxObject读取execl文件到tablewidget
时间: 2024-02-02 12:02:59 浏览: 85
QT读取excel,使用QAxObject
3星 · 编辑精心推荐
可以使用 QAxObject 类来读取 Excel 文件中的数据,并将其显示在 Qt 的 TableWidget 控件中。以下是一个简单的示例代码:
```cpp
#include <QAxObject>
#include <QTableWidget>
void readExcelFile(QString fileName, QTableWidget *tableWidget)
{
QAxObject excel("Excel.Application", 0);
QAxObject *workbooks = excel.querySubObject("Workbooks");
QAxObject *workbook = workbooks->querySubObject("Open(const QString&)", fileName);
QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);
QAxObject *usedrange = worksheet->querySubObject("UsedRange");
QAxObject *rows = usedrange->querySubObject("Rows");
QAxObject *columns = usedrange->querySubObject("Columns");
int rowCount = rows->property("Count").toInt();
int columnCount = columns->property("Count").toInt();
tableWidget->setRowCount(rowCount);
tableWidget->setColumnCount(columnCount);
for (int i = 1; i <= rowCount; i++) {
for (int j = 1; j <= columnCount; j++) {
QAxObject *cell = worksheet->querySubObject("Cells(int,int)", i, j);
QVariant value = cell->dynamicCall("Value()");
QString strValue = value.toString();
tableWidget->setItem(i - 1, j - 1, new QTableWidgetItem(strValue));
delete cell;
}
}
delete columns;
delete rows;
delete usedrange;
delete worksheet;
workbook->dynamicCall("Close()");
delete workbook;
delete workbooks;
excel.dynamicCall("Quit()");
}
```
调用示例:
```cpp
QTableWidget *tableWidget = new QTableWidget(this);
readExcelFile("test.xlsx", tableWidget);
```
其中,"test.xlsx" 为 Excel 文件名,tableWidget 为要显示数据的 TableWidget 控件。
阅读全文