傳統的讀取方式是通過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+"]";