首页 > 数据库技术 > 详细

Qt通过odbc读取excel数据

时间:2015-11-11 22:06:17      阅读:475      评论:0      收藏:0      [点我收藏+]

传统的读取方式是通过Excel.Application,这种方式不仅操作繁琐,而且速度也不快。

通过odbc读取,可以使用select语句直接读取整个工作表,处理excel数据就跟数据库一样方便。

当然,这种方式也有不足:

1、excel表格必须只能有一行表头。

2、相对于Excel.Application,无法准确定位单元格。

3、工作表名相当于数据库表名,表头相当于字段名,所以excel格式必须的固定的,否则无法读取到数据

读取的代码如下:

//文件路径
QString filePath;
//桌面打开
//Qt4
//QString desktopDir=QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
//Qt 5
QString desktopDir=QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
filePath=QFileDialog::getOpenFileName(parent,"选择Excel",desktopDir,"*.xls");
if(filePath.isNull()){
    error="无法打开excel文件"; 
    return;
}
//读取excel
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC","excel");
if( !db.isValid())
{
    error="数据库驱动异常";
    return;  
}

QString dsn = "DRIVER={Microsoft Excel Driver (*.xls)};"
              "DSN=‘‘;DBQ="+filePath;
db.setDatabaseName(dsn);

// open connection
if( !db.open())
{
    error="无法打开数据库";
    return;  
}

QSqlQuery query(db);
QSqlRecord record;
QString tableName = "sheet1$"; //sheet名,$是必须的 
QString sql="select * from ["+tableName+"]";

Qt通过odbc读取excel数据

原文:http://www.cnblogs.com/ztzheng/p/4957303.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!