Qt-Excel-vba筆記



VBA簡介

VBAVisual Basic for Application的縮寫,是一種應用程序自動化語音。所謂應用程序自動化,是指通過程序或者腳本讓應用程序,例如讓Microsoft ExcelWord自動化完成一些工作。

VBA具有VB語言的大多數特徵和易用性,它最大特點就是將Excel作爲開發平臺來開發應用程序,可以應用Excel的所有已有功能,例如數據處理、圖表繪製、數據庫連接、內置函數等等。

VBA開發環境

VBA集成開發環境(IDEIntegrated Development Environment)是進行VBA程序設計和代碼編寫的地方,同一版本的Office共享同一IDEVBA代碼和Excel文件是保存在一起的,可以通過點擊“工具——宏——Visual Basic編輯器”打開VBAIDE環境,進行程序設計和代碼編寫。

Excel對象的主要層次結構

Application對象->Workbook對象->Worksheet對象->Range對象

QT操作Excel

使用QAxObject組件可以方便的使用Office套件的API,QAxObjectCOM對象進行了封裝,QAxObject派生自QAxBase,而QAxBase提供了一組API,該API通過IUnknown指針直接訪問COM對象,我們這裏講的Excel也是一個COM對象,可以通過QAxObject來操作它。

新建一個excel

QAxObject *pApplication = NULL;

QAxObject *pWorkBooks = NULL;

QAxObject *pWorkBook = NULL;

QAxObject *pSheets = NULL;

QAxObject *pSheet = NULL;

void newExcel(const QString &fileName)

{

    pApplication = new QAxObject();

    pApplication->setControl("Excel.Application");//連接Excel控件

    pApplication->dynamicCall("SetVisible(bool)", false);//false不顯示窗體

    pApplication->setProperty("DisplayAlerts", false);//不顯示任何警告信息。

    pWorkBooks = pApplication->querySubObject("Workbooks");

    QFile file(fileName);

    if (file.exists())

{

        pWorkBook = pWorkBooks->querySubObject("Open(const QString &)", fileName);

    }

    else

    {

        pWorkBooks->dynamicCall("Add");

        pWorkBook = pApplication->querySubObject("ActiveWorkBook");

    }

    pSheets = pWorkBook->querySubObject("Sheets");// 得到Sheets對象的指針

pSheet = pSheets->querySubObject("Item(int)", 1);// 得到第一個sheet對象的指針

//pSheet = pSheets->querySubObject("Item(const QVariant)", QVariant(“AAA”));// 得到第一個sheet對象的指針}

}

 

增加1Worksheet(插入至最後一行)

void appendSheet(const QString &sheetName)
{
    int cnt = pSheets->querySubObject(“Item(int)”).toInt();// 獲取工作表數目
    QAxObject *pLastSheet = pSheets->querySubObject("Item(int)", cnt);
    pSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());
    pSheet = pSheets->querySubObject("Item(int)", cnt);
    pLastSheet->dynamicCall("Move(QVariant)", pSheet->asVariant());
    pSheet->setProperty("Name", sheetName);
}
 

刪除1Worksheet

void deletedSheet(const QString &sheetName)
{

pSheet = pSheets->querySubObject("Item(const QVariant)", QVariant(sheetName));

pSheet->dynamicCall(“Delete”);

}
 

Excel單元格中寫入數據

void setCellValue(int row, int column, const QString &value)
{
    QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column);
    pRange->dynamicCall("Value", value);
}

 

釋放Excel

void  freeExcel()

{
    if (pApplication != NULL)
    {
        pApplication->dynamicCall("Quit()");
        delete pApplication;
        pApplication = NULL;
    }
}

 

 

 

 

 

 

 

 //獲取標題

QVarianttitle_value = excel.property("Caption");

//操作單元格(第2行第2列)

QAxObject *cell =work_sheet->querySubObject("Cells(int,int)", 2, 2);

//設置單元格值

cell->setProperty("Value","ABC");  

//設置單元格行高

cell->setProperty("RowHeight",50);

//設置單元格列寬 

cell->setProperty("ColumnWidth",30);  

//左對齊(xlLeft):-4131  居中(xlCenter):-4108  右對齊(xlRight):-4152

cell->setProperty("HorizontalAlignment",-4108);

//上對齊(xlTop-4160 居中(xlCenter):-4108  下對齊(xlBottom):-4107

cell->setProperty("VerticalAlignment",-4108);  

 //內容過多,自動換行

 cell->setProperty("WrapText",true);

//清空單元格內容

cell->dynamicCall("ClearContents()"); 

//設置單元格背景色(綠色)

QAxObject* interior =cell->querySubObject("Interior");

interior->setProperty("Color",QColor(0, 255, 0));  

//設置單元格邊框色(藍色)

QAxObject* border =cell->querySubObject("Borders"); 

border->setProperty("Color",QColor(0, 0, 255));  

//獲取單元格字體

QAxObject *font =cell->querySubObject("Font");

 //設置單元格字體

font->setProperty("Name",QStringLiteral("華文彩雲"));

//設置單元格字體加粗

font->setProperty("Bold",true);

//設置單元格字體大小

font->setProperty("Size", 20);

//設置單元格字體斜體

font->setProperty("Italic",true);

//設置單元格下劃線

font->setProperty("Underline",2);

//設置單元格字體顏色(紅色)

font->setProperty("Color",QColor(255, 0, 0));

//自動保存文件

work_book->dynamicCall("Save()");

 //另存爲另一個文件 

 work_book->dynamicCall("SaveAs(constQString&)", "E:\\test2.xlsx");

 //關閉文件

work_book->dynamicCall("Close(Boolean)",false);

//退出

excel.dynamicCall("Quit(void)"); 

//合併單元格
//mergeRange = sheet->querySubObject("Rows(int)", iRowCount);
mergeRange = sheet->querySubObject("Range(QVariant)",tr("A%1:L%2").arg(iRowCount).arg(iRowCount));
mergeRange->dynamicCall("Merge(QVariant)", "false");
//自動展開到合適寬度
QAxObject *autoFitRange = sheet->querySubObject("Columns(A:I)");
autoFitRange->dynamicCall("AutoFit");

 

 

void EvaExcel::ToExcel(char* strPath,const Result* pResult)

{

       try

       {

              // 獲取一個Excel對象

              //QAxWidget excel("Excel.Application");     //Widgets must be created in the GUIthread

              QAxObject excel("Excel.Application");

              if(excel.isNull()) return;

 

              // 得到Workbooks集合的指針

              QAxObject* workbooks= excel.querySubObject("Workbooks");

              if(workbooks == NULL ) return;

 

              workbooks->dynamicCall(("Open(const QString&"),strPath);

 

              excel.setProperty("Caption","QtExcel");

              ////添加一個新的工作簿

              //workbooks->dynamicCall("Add");

 

              //獲取當前工作簿

              QAxObject* workbook= excel.querySubObject("ActiveWorkBook");

              if(workbook == NULL ) return;

 

              //得到Sheets對象的指針

              QAxObject* sheets= workbook->querySubObject("Sheets");

              if(sheets == NULL ) return;

 

              //獲取工作表集合中的工作表,即sheet1

              QAxObject* worksheet= sheets->querySubObject("Item(const QVariant &)",QVariant("Sheet1"));

              if(worksheet == NULL ) return;

 

              //設置sheet1工作爲選中狀態

              worksheet->dynamicCall("Select()");

 

              //獲取起始行

              QAxObject *used_range= worksheet->querySubObject("UsedRange");

              QAxObject *rows= used_range->querySubObject("Rows");

              int row_start = used_range->property("Row").toInt();

              //獲取行數

              int row_count = rows->property("Count").toInt();

             

              worksheet->querySubObject("Rows(int)",1)->querySubObject("insert()");

              worksheet->querySubObject("Rows(int)",2)->querySubObject("insert()");

              worksheet->querySubObject("Rows(int)",3)->querySubObject("insert()");

              worksheet->querySubObject("Rows(int)",4)->querySubObject("insert()");

              worksheet->querySubObject("Range(const QVariant&)",QVariant("A4:H4"))->querySubObject("Merge()");

 

              QString qstrTemp;

              qstrTemp = pResult->GetTestDate();

              qstrTemp +="            ";

              qstrTemp += pResult->GetTestTime();

              qstrTemp +="            ";

              qstrTemp += pResult->GetSampleName();

 

              QAxObject *cellX= worksheet->querySubObject("Cells(int,int)",1,1);  // x,y

              if(cellX == NULL)

              {

                     workbook->dynamicCall("Close()");

                     excel.dynamicCall("Quit()");

                     return;

              }

              QAxObject *fontX= cellX->querySubObject("Font");

              fontX->setProperty("Name",QString("Microsoft YaHei"));

              fontX->setProperty("Size",14);

              //cellX->setProperty("HorizontalAlignment",-4108);//xlCenter

              cellX->setProperty("ColumnWidth",12);

              cellX->dynamicCall("SetValue(const QVariant&)",QVariant(qstrTemp));

              worksheet->querySubObject("Range(const QVariant&)",QVariant("A1:H1"))->querySubObject("Merge()");

 

              QString qstrContent= pResult->GetContent();

              SplitResultToList(qstrContent);

 

              QVector<ResultTable*>::iterator iter;

              int i = 1;

              for(iter = m_ResultExcel.begin();iter != m_ResultExcel.end();++iter)

              {

                     QString strName= (*iter)->GetEleName();

                     QString strContent= (*iter)->GetEleContent();

 

                     QAxObject *cell2= worksheet->querySubObject("Cells(int,int)",2,i); // x,y

                     if(cell2 == NULL)

                     {

                            workbook->dynamicCall("Close()");

                            excel.dynamicCall("Quit()");

                            return;

                     }

                     QAxObject *font2= cell2->querySubObject("Font");

                     font2->setProperty("Name",QString("Microsoft YaHei"));

                     font2->setProperty("Size",14);

                     cell2->setProperty("HorizontalAlignment", -4108);//xlCenter

                     cell2->setProperty("ColumnWidth",12);

                     cell2->dynamicCall("SetValue(const QVariant&)",QVariant(strName));

 

                     QAxObject *cell3= worksheet->querySubObject("Cells(int,int)",3,i); // x,y

                     if(cell3 == NULL)

                     {

                            workbook->dynamicCall("Close()");

                            excel.dynamicCall("Quit()");

                            return;

                     }

                     QAxObject *font3= cell3->querySubObject("Font");

                     font3->setProperty("Name",QString("Microsoft YaHei"));

                     font3->setProperty("Size",14);

                     cell3->setProperty("HorizontalAlignment", -4108);//xlCenter

                     cell3->setProperty("ColumnWidth",12);

                     cell3->dynamicCall("SetValue(const QVariant&)",QVariant(strContent));

 

                     i++;

              }

              workbook->querySubObject("Save()");

 

              //關閉工作簿

              workbook->dynamicCall("Close()");

              //關閉excel

              excel.dynamicCall("Quit()");

 

       }

       catch(...)

       {

              return ;

       }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章