最近有客戶需要去讀取excel檔案的資料

接著再使用資料去做其他功能

在開始之前必須先在pro檔案裡加入

CONFIG+=qaxcontainer

否則會出現 link error

接著在

#include<QAxObject>

完成前置動作

接著下來直接看內容吧

QString fileName=QFileDialog::getOpenFileName(this,tr("Import file")
,qApp->applicationDirPath(),tr("Excel Files (*.xls)"));
//開啟file dialog供使用者去選擇檔案路徑
 
QAxObject excel("Excel.Application");//選擇excel控件
 
excel.setProperty("Visible",false);
 
QAxObject* workbooks=excel.querySubObject("WorkBooks");
//得到工作簿集合
 
workbooks->dynamicCall("Open (const QString&)",fileName);
//開啟選擇路徑的檔案
 
QAxObject* workbook=excel.querySubObject("ActiveWorkBook");
//得到活動工作簿
 
QAxObject* worksheets=workbook->querySubObject("WorkSheets(int)", 1);
//得到第一個工作表
 
QAxObject* usedrange=worksheets->querySubObject("UsedRange");
QAxObject* rows=usedrange->querySubObject("Rows");
QAxObject* columns=usedrange->querySubObject("Columns");
 
int nCols=columns->property("Count").toInt();
int nRows=rows->property("Count").toInt();
//行數和列數
 
for(inti=1;i<nRows;i++)//行
{
    for(intj=1;j<nCols;j++)//列
{
          QAxObject*cell=worksheets->
              querySubObject("Cells(int,int)",i,j);//單元格
 
          qDebug()<<i<<j<<
          cell->dynamicCall("Value2()").toString();
}
}
//得到excel資料
 
workbook->dynamicCall("Close (Boolean)",false);
excel.dynamicCall("Quit (void)");

這裡發文排序的方式有點亂

也請各位見諒
arrow
arrow
    全站熱搜

    力寶 發表在 痞客邦 留言(1) 人氣()