Qt读取excel
使用 odbc 和 QtXlsxWriter 读 xls 和 xlsx 格式的 excel 文件,使用 odbc 读 xlsx 会链接失败,使用 QtXlsxWriter 读 xls 也无法读取,所以只好针对两种格式分别处理,使用 odbc 和 QtXlsxWriter 的好处是不用在目标机器上安装 excel 。
- 安装 QtXlsxWriter:
在 https://github.com/dbzhang800/QtXlsxWriter 下载源码。
下载安装 perl
使用Qt命令行cd到QtXlsxWriter目录,然后执行:
qmake
make
make install
mingw改成
qmake
mingw32-make
mingw32-make install
执行完毕就安装完成了。
- 读取:
在工程文件中加入:
QT += sql xlsx
头文件包含:
#include <QString>
#include <QDebug>
#include <QStandardPaths>
#include <QFileDialog>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery>
#include <QtXlsx/QtXlsx>
cpp:
bool BP_ExcelImport::read_excel()
{
QString desktopDir = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QString filePath = QFileDialog::getOpenFileName(NULL,"选择导入文件",desktopDir,"*.xls;*.xlsx");
if(filePath.isNull())
{
qDebug()<<"未选择导入文件.";
return false;
}
if(0 == filePath.right(4).compare(".xls",Qt::CaseInsensitive))
return read_xls(filePath);
else if(0 == filePath.right(5).compare(".xlsx",Qt::CaseInsensitive))
return read_xlsx(filePath);
qDebug()<<QString("选择了非excel文件:") + filePath;
return true;
}
//读 xlsx
bool BP_ExcelImport::read_xlsx(const QString & path)
{
QXlsx::Document xlsx(path);
QString s;
for(int i = 0;i < 2;++i)
for(int j = 1;j < 19;++j)
s = s + xlsx.read(QString('A' + i) + QString::number(j)).toString() + "\r\n";
QMessageBox(QMessageBox::Information,"message",s).exec();
return true;
}
//读 xls
bool BP_ExcelImport::read_xls(const QString & path)
{
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString dsn ="DRIVER={Microsoft Excel Driver (*.xls)};DSN='';DBQ=" + path;
db.setDatabaseName(dsn);
if(db.open())
{
QSqlQuery query(db);
query.exec("select * from [" + QString("Sheet1") + "$]");
QString s;
while (query.next())
s = s + query.value(0).toString() + " " + query.value(1).toString() + "\r\n";
QMessageBox(QMessageBox::Information,"message",s).exec();
}
else
{
QSqlError error = db.lastError();
qDebug()<<QString("xls db open failed:")+error.driverText()+("\r\nerror type:")+QString::number(error.type())+"\r\n";
return false;
}
return true;
}
效果:
ODBC的方式读不出来excel的第一行,也没找到读取的方法,怀疑是第一行被认为是表头了。