QT快速讀取Excel
阿新 • • 發佈:2019-01-06
1 //QT+=axcontainer 2 3 #include <QFileDialog> 4 #include <QAxObject> 5 #include <QVariant> 6 #include <QList> 7 8 void getExcelContent(QList<QList<QVariant>>& result) 9 { 10 QString filePath=QFileDialog::getOpenFileName( 11 this, QStringLiteral("選擇Excel檔案"), "", 12 QStringLiteral("Exel file(*.xls *.xlsx)")); 13 if(filePath.isEmpty)return; 14 15 QAxObject* excel=new QAxObject(this); 16 excel->setControl("Excel.Application");//連線Excel控制元件 17 excel->dynamicCall("SetVisible (bool Visible)","false");//不顯示窗體 18 excel->setProperty("DisplayAlerts", false);//不顯示任何警告資訊。如果為true那麼在關閉是會出現類似“檔案已修改,是否儲存”的提示 19 20 //開啟檔案 21 QAxObject *workbooks = excel->querySubObject("WorkBooks");//獲取工作簿集合 22 QAxObject *workbook = excel->querySubObject("Open (const QString &)", filePath);//獲取當前工作簿 23 24 //開啟表 25 //QAxObject *worksheets = workbook->querySubObject("Sheets");//獲取工作表集合 26 QAxObject *worksheet = worksheets->querySubObject("Item(int)",1);//工作表1,即sheet1 27 28 //獲取表中的資料到QVariant中 29 QAxObject *usedRange=worksheet->querySubObject("UsedRange"); 30 QVariant var=usedRange->dynamicCall("value"); 31 32 QVariantList varRowContents=var.toList(); 33 const int rowCount=varRowContents.size(); 34 QVariantList tmp; 35 for(int i=0; i<rowCount; ++i) 36 { 37 tmp=varRowContents[i].toList(); 38 result.append(tmp); 39 } 40 }