QAxObject读取excel并显示到QTableView
时间: 2023-09-11 20:10:49 浏览: 101
您可以使用 Qt 的 QAxObject 类来连接并读取 Excel 文件中的数据,然后将其显示在 QTableView 上。以下是可能的代码示例:
// 创建 QAxObject 实例,连接 Excel 应用程序
QAxObject *excel = new QAxObject("Excel.Application");
// 隐藏 Excel 程序的窗口
excel->setProperty("Visible", false);
// 打开指定的 Excel 文件
QAxObject *workbooks = excel->querySubObject("Workbooks");
QAxObject *workbook = workbooks->querySubObject("Open(const QString&)", "filepath");
// 获取指定的工作表,读取和导出数据
QAxObject *sheets = workbook->querySubObject("Sheets");
QAxObject *sheet = sheets->querySubObject("Item(int)", 1);
// 获取指定范围的单元格数据
QAxObject *used_range = sheet->querySubObject("UsedRange");
QAxObject *rows = used_range->querySubObject("Rows");
QAxObject *columns = used_range->querySubObject("Columns");
int num_rows = rows->property("Count").toInt();
int num_cols = columns->property("Count").toInt();
// 将数据导出到 QTableWidget 中
QTableWidget *table = new QTableWidget(parent);
table->setRowCount(num_rows);
table->setColumnCount(num_cols);
for (int i = 1; i <= num_rows; ++i)
{
for (int j = 1; j <= num_cols; ++j)
{
QAxObject *cell = sheet->querySubObject("Cells(int,int)", i, j);
QVariant value = cell->dynamicCall("Value");
table->setItem(i - 1, j - 1, new QTableWidgetItem(value.toString()));
cell->clear();
delete cell;
}
}
// 删除对象
delete table;
sheet->deleteLater();
used_range->deleteLater();
columns->deleteLater();
rows->deleteLater();
sheet->deleteLater();
workbook->close();
workbook->deleteLater();
workbooks->deleteLater();
excel->deleteLater();
阅读全文