Qt通过odbc读取excel数据

传统的读取方式是通过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+"]";
posted @ 2015-11-11 20:47  Mr.郑  阅读(4434)  评论(1编辑  收藏  举报