您的位置:首页 > 编程语言 > Qt开发

Qt通过odbc读取excel数据

2015-11-11 20:47 453 查看
传统的读取方式是通过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+"]";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: