QT 通过QAxObject与本地应用程序读取Excel内容
首先在配置中加入
QT += axcontainer
在开发过程中,经常需要与Excel文件进行交互,例如读取数据、写入数据或进行格式设置。Qt提供了一个强大的类QAxObject,通过它可以方便地操作Excel文件。
QAxObject excel("ket.Application");
if (excel.isNull()) {
QMessageBox::critical(this, "错误", "没有发现Excel可执行程序,请安装WPS");
return;
}
excel.setProperty("Visible", false);
QAxObject *workbooks = excel.querySubObject("Workbooks");
if (!workbooks) {
QMessageBox::critical(this, "错误", "无法访问文件!");
return;
}
workbooks->dynamicCall("Open(const QString&)", xlsPath);
QAxObject * workbook = excel.querySubObject("ActiveWorkBook");
QAxObject *sheet = workbook->querySubObject("Worksheets(int)", 1);
if (!sheet) {
QMessageBox::critical(this, "错误", "无法访问表格1!");
return;
}
QAxObject *usedRange = sheet->querySubObject("UsedRange");
if (!usedRange) {
QMessageBox::critical(this, "错误", "无法访问使用范围!");
return;
}
QAxObject *rows = usedRange->querySubObject("Rows");
QAxObject *columns = usedRange->querySubObject("Columns");
int rowCount = rows->property("Count").toInt();
int colCount = columns->property("Count").toInt();
for (int row = 1; row <= rowCount; ++row) {
for (int col = 1; col <= colCount; ++col) {
QAxObject *cell = sheet->querySubObject("Cells(int,int)", row, col);
QString cellValue = cell->dynamicCall("Value2()").toString();
delete cell;
}
}