Qt之如何读取Excel表格数据
概述:
大家好我是背锅侠“IT幻想家”, 今天唠叨一下Qt读取Excel需要注意的几个重要的点(个人理解):
1.Qt环境4.8.5或4.8.3下是有读取Excel的模块的,但是存在Bug的在你构建工程时会报找不到模块库
2.Excel环境,首先你的Excel一定是正版已经激活的软件,否则在你调用Excel的API函数时依旧会报错误
3.最重要的一点如果大家使用Debug进行调试一定要记得清理后台没有关闭的Excel.exe
4.此工程不支持跨平台使用,比如在麒麟下Linux下都会报找不到QAxObject这个类的,因为这个类是WinDows下的
代码示例:
.pro:
QT += axcontainer //5.4.1
CONFIG += qaxcontainer //因版本问题写的方式不同
需要包含的头文件:
#include <QVariant> //读取出的数据只能用此类型容器进行存储
#include <ActiveQt/QAxObject> //Excel
readExcelData.h:
/**
* @brief readExcelData 读取Excel数据
* @return saveCloseQuit();
*/
bool readExcelData();
private:
QAxObject* excel; //操作Excel文件对象(open-save-close-quit)
QAxObject* workbooks; //总工作薄对象
QAxObject* workbook; //操作当前工作薄对象
QAxObject* worksheets; //文件中所有<Sheet>表页
QAxObject* worksheet; //存储第n个sheet对象
QAxObject* usedrange; //存储当前sheet的数据对象
readExcelData.cpp:
ExcelRead::ExcelRead()
{
excel = NULL; //在构造函数中进行初始化操作
workbooks = NULL;
workbook = NULL;
worksheets = NULL;
worksheet = NULL;
usedrange = NULL;
}
bool ExcelRead::readExcelData()
{
excel = new QAxObject("Excel.Application"); //创建Excel对象连接驱动
excel->dynamicCall("SetVisible(bool)",true); //ture的打开Excel表 false不打开Excel表
excel->setProperty("DisplayAlerts",false);
workbooks = excel->querySubObject("WorkBooks");
workbook = workbooks->querySubObject("Open(const QString&)",fileName); //打开指定Excel
worksheets = workbook->querySubObject("WorkSheets"); //获取表页对象
worksheet = worksheets->querySubObject("Item(int)",1); //获取第1个sheet表
usedrange =worksheet->querySubObject("Usedrange"); //获取权限
int iRow = usedrange->property("Row").toInt(); //数据起始行数和列数(可以解决不规则Excel)
int iCol = usedrange->property("Column").toInt();
int intRow = usedrange->querySubObject("Rows")->property("Count").toInt(); //获取数据总行数
// 逐行读取主表
for (int i = iRow; i <= intRow; i++)
{
QString number = worksheet->querySubObject("Cells(int,int)",i,1)->dynamicCall(("Value2()")).value<QString>();
QString name = worksheet->querySubObject("Cells(int,int)",i,2)->dynamicCall(("Value2()")).value<QString>();
QString id = worksheet->querySubObject("Cells(int,int)",i,3)->dynamicCall(("Value2()")).value<QString>();
QString desc = worksheet->querySubObject("Cells(int,int)",i,4)->dynamicCall(("Value2()")).value<QString>();
qDebug() << number << name << id << desc;//打印验证数据
}
return saveCloseQuit();
}
over:
欢迎大家关注作者在文末评论、点赞、转发以及批评指正!
如果大家有更好的方法或有问题可以在文末评论一起讨论!
共同学习!
共同进步!
向内认知,向外行走!