Qt读取excel文件的两种方法
程序员文章站
2024-03-17 19:20:58
...
一.QAxObject
1.在工程文件(pro文件)中加入
CONFIG += qaxcontainer
2.添加头文件
#include <QAxObject>
3.读取文件代码
QAxObject excel("Excel.Application");
excel.setProperty("Visible", false); //隐藏打开的excel文件界面
QAxObject *workbooks = excel.querySubObject("WorkBooks");
QAxObject *workbook = workbooks->querySubObject("Open(QString, QVariant)", "文件名"); //打开文件
QAxObject * worksheet = workbook->querySubObject("WorkSheets(int)", 1); //访问第一个工作表
QAxObject * usedrange = worksheet->querySubObject("UsedRange");
QAxObject * rows = usedrange->querySubObject("Rows");
int intRows = rows->property("Count").toInt(); //行数
QString Range = "A1:B" +QString::number(intRows);
QAxObject *allEnvData = worksheet->querySubObject("Range(QString)", Range); //读取范围
QVariant allEnvDataQVariant = allEnvData->property("Value");
QVariantList allEnvDataList = allEnvDataQVariant.toList();
for(int i=0; i< intRows; i++)
{
QVariantList allEnvDataList_i = allEnvDataList[i].toList() ;
QString data1 = allEnvDataList_i[0].toString(); //第i行第0列的数据
}
workbooks->dynamicCall("Close()");
excel.dynamicCall("Quit()");
二.ODBC
1.在工程文件(pro文件)中加入
QT += sql
2.添加头文件
#include <QSqlDatabase>
#include <QSqlQuery>
3.读取文件代码
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", "excelexport");
if(!db.isValid())
{
return;
}
QString dsn="Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};Readonly=TRUE;DBQ="+"文件名"+ ";";
db.setDatabaseName(dsn);
if(!db.open())
{
return;
}
QSqlQuery query(db);
query.exec("select * from [Sheet1$]");
while (query.next())
{
QString data1 = query.value(0).toString();
}
db.close();