Qt 對Excel的操作封裝

推薦使用: QXlsx
https://github.com/QtExcel/QXlsx

---------------------------

.pro

QT  += axcontainer


#ifndef ADVANCEEXCEL_H
#define ADVANCEEXCEL_H


#include <QString>
#include <QVariant>

#include "excitingexcel_global.h"


class QAxObject;

class EXCITINGEXCELSHARED_EXPORT AdvanceExcel : public QObject
{
    Q_OBJECT

public:
    AdvanceExcel(QString xlsFilePath, QObject *parent = nullptr);
    ~AdvanceExcel();

public:
    QAxObject * getWorkBooks();
    QAxObject * getWorkBook();
    QAxObject * getWorkSheets();
    QAxObject * getWorkSheet();

public:
    /**************************************************************************/
    /* 工作表*/
    /**************************************************************************/
    //sheetIndex 起始於 1
    //選擇工作表
    bool selectSheet(int nSheetIndex);
    bool selectSheet(const QString& strSheetName);


    //刪除工作表
    bool deleteSheet(int nSheetIndex);
    bool deleteSheet(const QString& strSheetName);

    //插入工作表
    bool insertSheet(const QString& strSheetName, bool bAtLast = true);


    //獲取工作表數目
    int getSheetsCount();

    //獲取工作表名稱 (在 selectSheet() 之後纔可調用)
    QString getSheetName();
    QString getSheetName(int nSheetIndex);

    /**************************************************************************/
    /* 單元格*/
    /**************************************************************************/
    // 設置單元格內容
    bool setCellString(int nRow, int nColumn, const QString& strValue);
    //strCell 例如 "A7"
    bool setCellString(const QString& strCell, const QString& strValue);

    bool setCellString(const QString& strCell, const QStringList& strValues);

    bool setCellStringx(const QString& strCell, const QString& strValue);

    //合併單元格. range 例如 "A5:C7"
    bool mergeCells(const QString& strCell);
    bool mergeCells(int nTopLeftRow, int nTopLeftColumn, int nBottomRightRow, int nBottomRightColumn);

    //獲取單元格內容
    QVariant getCellValue(int nRow, int column);

    //清空單元格內容
    void clearCell(int nRow, int column);
    void clearCell(const QString& strCell);

    void setCellFont(int nRow, int column, int nColor);
    void setCellFont(const QString& strCell, int nColor);

    // 0 無色 1黑 2白 3紅 4 綠 5藍  6黃 7紫 8青
    void setFontColor(int nRow, int nColumn,int nFontColor);
    void setFontColor(const QString& strCell, int nFontColor);

    // 字體
    void setCellFontBold(int nRow, int column, bool bBold = true);
    void setCellFontBold(const QString& strCell, bool bBold = true);
    void setCellFontSize(int nRow, int column, int size);
    void setCellFontSize(const QString& strCell, int size);


    //設置單元格邊框色
   void setCellBgColor(int nRow, int column, int nColor);
   void setCellBgColor(const QString& strCell, int nColor);

     //設置單元格邊框色
    void setCellBorderColor(int nRow, int column, int nColor);
    void setCellBorderColor(const QString& strCell, int nColor);

    // 在指定行後插入一空行
    bool insertEmptyRow(int nInsertRow  =1);
    bool insertEmptyColumn(int nInsertCol  =1);

    // 複製行/列並插入
    bool copyRowThenInsert(int nCopyRow, int nInsertRow);
    bool copyColumnThenInsert(int nCopyCol, int nInsertCol);

    // 複製行/列並粘貼
    bool copyRowThenPaste(int nCopyRow, int nInsertRow);
    bool copyColumnThenPaste(int nCopyCol, int nInsertCol);

    // 區域複製插入
    bool copyBlockThenInsert(const QString& strCellCopy, const QString& strCellPast);
    bool copyBlockThenPaste(const QString& strCellCopy, const QString& strCellPast);

    bool multiSelectCopy(const QString &strCellCopy, const QString &strCellPaste);

    // 刪除指定的行 列
    bool deleteRow(int nRowNum);
    bool deleteColumn(int nColumnNum);

    // 單元格求和, 將要累加的單元格進行累加後,存入 strCellResult
    bool  sumFunc(const QString& strCell, const QString& strCellResult);
    bool  sumFunc(const QStringList& strCells, const QString& strCellResult);

    // 合計

    // 插入行

    // 插入列

    /**************************************************************************/
    /* 佈局格式*/
    /**************************************************************************/

    //設置單元格列寬
    void setColumnWidth(int column, int width);

    //設置單元格行高
    void setRowHeight(int nRow, int height);

    //居中對齊(xlCenter):-4108
    void setCellTextCenter(int nRow, int column);
    void setCellTextCenter(const QString& strCell);

    void setCellTextLeft(int nRow, int column);
    void setCellTextLeft(const QString& strCell);

    void setCellTextRight(int nRow, int column);
    void setCellTextRight(const QString& strCell);

    //文本自動換行
    void setCellTextWrap(int nRow, int column, bool isWrap = true);
    void setCellTextWrap(const QString& strCell, bool isWrap = true);

    //自適應列寬
    void setAutoFitRow(int nRow);
    void setAutoFitCol(int nColumn);

    void mergeSerialSameCellsInAColumn(int column, int topRow);

    // 獲取數據佔用行列
    int getUsedRowsCount();
    int getUsedColumnsCount();
    void getUsedRange(int* nTopLeftRow, int* nTopLeftColumn, int* nBottomRightRow, int* nBottomRightColumn);



    /**************************************************************************/
    /* 文件 */
    /**************************************************************************/
    void save();
    void saveAs(const QString& strPath);
    void close();

public slots:
    void onAxWidgetException(int, const QString &, const QString &, const QString &);

private:
    QAxObject* m_pExcel = nullptr;

    QAxObject* m_pWorkBook = nullptr;
    QAxObject* m_pWorkBooks = nullptr;

    QAxObject* m_pWorkSheet = nullptr;
    QAxObject* m_pWorkSheets = nullptr;

    QAxObject* m_pAxObj = nullptr;
};

#endif // ADVANCEEXCEL_H


.


#include "AdvanceExcel.h"


#include <QAxObject>
#include <QFile>
#include <QStringList>
#include <QDebug>

#include "AdvanceExcel.h"

#include <objbase.h>


// 清理指針
#define DEL_OBJ(X) {if(X){ delete X; X=nullptr;}}



AdvanceExcel::AdvanceExcel(QString xlsFilePath, QObject *parent)
{
    CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    m_pExcel = new QAxObject("Excel.Application", parent);
    //m_pExcel = new QAxObject("Ket.Application");

    m_pExcel->dynamicCall("SetVisible(bool)", true); //true 表示操作文件時可見,false表示爲不可見
    m_pExcel->setProperty("DisplayAlerts", false);  // 設置屬性

    m_pWorkBooks = m_pExcel->querySubObject("WorkBooks");   // 獲取某一個子對象
    QFile file(xlsFilePath);
    if (file.exists())
    {
        //m_pWorkBooks->dynamicCall("Open(const QString&)", xlsFilePath);
        m_pWorkBook = m_pWorkBooks->querySubObject("Open(const QString&)", xlsFilePath);
        //m_pWorkBook = m_pExcel->querySubObject("ActiveWorkBook");
        m_pWorkSheets = m_pWorkBook->querySubObject("WorkSheets");
    }
    else
    {
        m_pWorkBooks->dynamicCall("Add");
        m_pWorkBook = m_pExcel->querySubObject("ActiveWorkBook");
        m_pWorkBook->dynamicCall("SaveAs (const QString&, int, const QString&, const QString&, bool, bool)",
                                 xlsFilePath, 56, QString(""), QString(""), false, false);

        m_pWorkSheets = m_pWorkBook->querySubObject("WorkSheets");
    }

    //    connect(
    //            m_pAxObj,
    //            SIGNAL(exception(int, const QString &, const QString &, const QString &)),
    //            this,
    //            SLOT(onAxWidgetException(int, const QString &, const QString &, const QString &)));
}


AdvanceExcel::~AdvanceExcel()
{
    close();
}



QAxObject* AdvanceExcel::getWorkBooks()
{
    return m_pWorkBooks;
}


QAxObject* AdvanceExcel::getWorkBook()
{
    return m_pWorkBook;
}


QAxObject* AdvanceExcel::getWorkSheets()
{
    return m_pWorkSheets;
}


QAxObject* AdvanceExcel::getWorkSheet()
{
    return m_pWorkSheet;
}


bool AdvanceExcel::selectSheet(int nSheetIndex)
{
    if(m_pWorkSheets)
    {
        m_pWorkSheet = m_pWorkSheets->querySubObject("Item(int)", nSheetIndex);
        return true;
    }
    return false;
}


bool AdvanceExcel::selectSheet(const QString& strSheetName)
{
    if(m_pWorkSheets)
    {
        m_pWorkSheet = m_pWorkSheets->querySubObject("Item(const QString&)", strSheetName);
        return true;
    }
    return false;
}


bool AdvanceExcel::deleteSheet(int nSheetIndex)
{
    if(m_pWorkSheets)
    {
        m_pAxObj = m_pWorkSheets->querySubObject("Item(int)", nSheetIndex);
        m_pAxObj->dynamicCall("delete");
        return true;
    }
    return false;
}


bool AdvanceExcel::deleteSheet(const QString& strSheetName)
{
    if(m_pWorkSheets)
    {
        m_pAxObj = m_pWorkSheets->querySubObject("Item(const QString&)", strSheetName);
        m_pAxObj->dynamicCall("delete");
        return true;
    }
    return false;
}


bool AdvanceExcel::insertSheet(const QString& strSheetName, bool bAtLast)
{
    if(m_pWorkSheets)
    {
        if(bAtLast)
        {
            m_pWorkSheets->querySubObject("Add()");//新建一個工作簿
            QAxObject* pAxObj = m_pWorkSheets->querySubObject("Item(int)", 1);//獲取工作表集合的工作表1
            pAxObj->setProperty("Name", strSheetName);
        }
        else
        {
            int nSheetCount = getSheetsCount();
            QAxObject* pLastSheet = m_pWorkSheets->querySubObject("Item(int)", nSheetCount);//這步可以的
            m_pWorkSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());//這步之後,新加表 處於倒數第二的位置;
            m_pWorkSheet = m_pWorkSheets->querySubObject("Item(int)", nSheetCount);
            pLastSheet->dynamicCall("Move(QVariant)", m_pWorkSheet->asVariant());
        }
        return true;
    }
    else
    {
        return false;
    }



    //    QAxObject *pWorkSheet = nullptr;
    //    try {
    //        int count = m_pWorkSheets->property("Count").toInt();  //獲取工作表數目
    //        QAxObject *pLastSheet = m_pWorkSheets->querySubObject("Item(int)", count);
    //        pWorkSheet = m_pWorkSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());
    //        pLastSheet->dynamicCall("Move(QVariant)", pWorkSheet->asVariant());
    //        pWorkSheet->setProperty("Name", strSheetName);  //設置工作表名稱
    //    } catch (...) {
    //        qCritical()<<"創建sheet失敗...";
    //    }
    //    return pWorkSheet;
}


int AdvanceExcel::getSheetsCount()
{
    return m_pWorkSheets->property("Count").toInt();    // 讀取屬
}


QString AdvanceExcel::getSheetName()
{
    if(m_pWorkSheet)
        return m_pWorkSheet->property("Name").toString();
    else
        return "";
}


QString AdvanceExcel::getSheetName(int nSheetIndex)
{
    if(m_pWorkSheets)
    {
        m_pAxObj = m_pWorkSheets->querySubObject("Item(int)", nSheetIndex);
        return m_pAxObj->property("Name").toString();
    }
    else
        return "";
}


bool AdvanceExcel::setCellString(int nRow, int nColumn, const QString &strValue)
{
    if(m_pWorkSheet)
    {
        m_pAxObj = m_pWorkSheet->querySubObject("Cells(int,int)", nRow, nColumn);
        m_pAxObj->dynamicCall("SetValue(const QString&)", strValue);
        return true;
    }
    else
    {
        return false;
    }
}


bool AdvanceExcel::setCellString(const QString &strCell, const QString &strValue)
{
    if(m_pWorkSheet)
    {
        m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
        m_pAxObj->dynamicCall("SetValue(const QString&)", strValue);
        return true;
    }
    else
    {
        return false;
    }

}

bool AdvanceExcel::setCellString(const QString &strCell, const QStringList &strValues)
{
    if(m_pWorkSheet)
    {
        m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&, const QString&,)", strCell);
        m_pAxObj->dynamicCall("SetValue(const QStringList&)",strValues);
        return true;
    }
    else
    {
        return false;
    }
}



bool AdvanceExcel::setCellStringx(const QString &strCell, const QString &strValue)
{
    //    QStringList lst;
    //    lst<<"1"<<"2"<<"3"<<"4"<<"5";

    //    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&, const QString&,)","D5","D14");
    //    //Cells->dynamicCall("SetValue(const QStringList&)",lst);
    //    int nxx = m_pAxObj->dynamicCall("Summary").toInt();

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strValue);

    m_pAxObj->dynamicCall("Sum(int, int, int )", 4, 65, 2);
    return true;


    if(m_pWorkSheet)
    {
        m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);

        connect(
                    m_pAxObj,
                    SIGNAL(exception(int, const QString &, const QString &, const QString &)),
                    this,
                    SLOT(onAxWidgetException(int, const QString &, const QString &, const QString &)));

        qDebug()<<m_pAxObj->property("Summary").toInt();
        qDebug()<<m_pAxObj->property("Summary").toString();


        qDebug()<<"Format: \t\t"<<m_pAxObj->property("NumberFormatLocal").toString();

        //        m_pAxObj->dynamicCall("AVERAGE()", strCell);
        //m_pAxObj->dynamicCall("Summary()", strCell);

        m_pAxObj->dynamicCall("xlSum(const QString&)", strCell);

        m_pAxObj->setProperty("NumberFormatLocal","@");
        qDebug()<<"Format: \t\t"<<m_pAxObj->property("NumberFormatLocal").toString();

        return true;
    }
    else
    {
        return false;
    }

    //->setProperty("NumberFormatLocal", "@");  // 設置爲文本
    //setProperty("NumberFormatLocal", "yyyy/m/d");

}



bool AdvanceExcel::mergeCells(const QString& strCell)
{
    if(!m_pWorkSheet) return false;

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    //range->setProperty("VerticalAlignment", -4108);//xlCenter
    //m_pAxObj->setProperty("WrapText", true);
    m_pAxObj->setProperty("MergeCells", true);
    return true;

}


bool AdvanceExcel::mergeCells(int topLeftRow, int nTopLeftColumn, int nBottomRightRow, int nBottomRightColumn)
{
    if(!m_pWorkSheet) return false;

    QString strCell;
    strCell.append(QChar(nTopLeftColumn - 1 + 'A'));
    strCell.append(QString::number(topLeftRow));
    strCell.append(":");
    strCell.append(QChar(nBottomRightColumn - 1 + 'A'));
    strCell.append(QString::number(nBottomRightRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("VerticalAlignment", -4108);//xlCenter
    //m_pAxObj->setProperty("WrapText", true);
    m_pAxObj->setProperty("MergeCells", true);
    return true;
}


QVariant AdvanceExcel::getCellValue(int nRow, int nColumn)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Cells(int,int)", nRow, nColumn);
    return m_pAxObj->property("Value");
}


void AdvanceExcel::clearCell(int nRow, int nColumn)
{
    QString strCell;
    strCell.append(QChar(nColumn - 1 + 'A'));
    strCell.append(QString::number(nRow));

    clearCell(strCell);
}


void AdvanceExcel::clearCell(const QString& strCell)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->dynamicCall("ClearContents()");
}


void AdvanceExcel::setCellFont(int nRow, int nColumn, int nColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Cells(int,int)", nRow, nColumn);
    QAxObject* pFont = m_pAxObj->querySubObject("Font");  //獲取單元格字體
    pFont->setProperty("Name", QStringLiteral("華文彩雲"));  //設置單元格字體
    pFont->setProperty("Bold", true);  //設置單元格字體加粗
    pFont->setProperty("Size", 20);  //設置單元格字體大小
    pFont->setProperty("Italic", true);  //設置單元格字體斜體
    pFont->setProperty("Underline", 2);  //設置單元格下劃線
    pFont->setProperty("Color", nColor);  //設置單元格字體顏色(紅色)
}


void AdvanceExcel::setCellFont(const QString &strCell, int nColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    QAxObject* pFont = m_pAxObj->querySubObject("Font");  //獲取單元格字體
    pFont->setProperty("Name", QStringLiteral("華文彩雲"));  //設置單元格字體
    pFont->setProperty("Bold", true);  //設置單元格字體加粗
    pFont->setProperty("Size", 20);  //設置單元格字體大小
    pFont->setProperty("Italic", true);  //設置單元格字體斜體
    pFont->setProperty("Underline", 2);  //設置單元格下劃線
    pFont->setProperty("Color", nColor);  //設置單元格字體顏色(紅色)
}


void AdvanceExcel::setFontColor(int nRow, int nColumn, int nFontColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Cells(int,int)", nRow, nColumn);
    m_pAxObj->querySubObject("Font")->setProperty("ColorIndex", nFontColor);
}


void AdvanceExcel::setFontColor(const QString &strCell, int nFontColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->querySubObject("Font")->setProperty("ColorIndex", nFontColor);
}


void AdvanceExcel::setCellBgColor(int nRow, int nColumn, int nColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Cells(int,int)", nRow, nColumn);
    QAxObject* border = m_pAxObj->querySubObject("Interior");
    border->setProperty("Color", nColor);
}


void AdvanceExcel::setCellBgColor(const QString &strCell, int nColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    QAxObject* border = m_pAxObj->querySubObject("Interior");
    border->setProperty("Color", nColor);

    //    QAxObject* pRange = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    //    range->dynamicCall("BorderAround", 1, 3, 3);

    //    range->dynamicCall("BorderAround", Style, Width,ColorIndex);
    //    Style值:0- no line; 1-solid; 2-big dot;3-small dot;4-dash dot; 5-dash dot dot;
    //    ColorIndex:1-black;2-white;3-red;4-green;5-blue; 6-yellow; 7-pink;8-dark blue;
}


void AdvanceExcel::setCellBorderColor(int nRow, int nColumn, int nColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Cells(int,int)", nRow, nColumn);
    QAxObject* border = m_pAxObj->querySubObject("Borders");
    border->setProperty("Color", nColor);

    //    QAxObject* pRange = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    //    range->dynamicCall("BorderAround", 1, 3, 3);

    //    QAxObject* border = strCell->querySubObject("Borders");
    //    border->setProperty("Color", QColor(0, 0, 255));   //設置單元格邊框色(藍色)
}


void AdvanceExcel::setCellBorderColor(const QString &strCell, int nColor)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj = m_pAxObj->querySubObject("Borders");
    m_pAxObj->setProperty("Color", nColor);

    //   Style值:0- no line; 1-solid; 2-big dot;3-small dot;4-dash dot; 5-dash dot dot;
    //   ColorIndex:1-black;2-white;3-red;4-green;5-blue; 6-yellow; 7-pink;8-dark blue;


    //    QAxObject* border = strCell->querySubObject("Borders");
    //    border->setProperty("Color", QColor(0, 0, 255));   //設置單元格邊框色(藍色)
}


bool AdvanceExcel::insertEmptyRow(int nInsertRow)
{
    if(m_pWorkSheet && nInsertRow < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Rows(int)", nInsertRow);
    m_pAxObj->dynamicCall("Insert()");
    return true;
}


bool AdvanceExcel::insertEmptyColumn(int nInsertCol)
{
    if(m_pWorkSheet && nInsertCol < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Columns(int)", nInsertCol);
    m_pAxObj->dynamicCall("Insert()");
    return true;
}


bool AdvanceExcel::copyRowThenInsert(int nCopyRow, int nInsertRow)
{
    if(!m_pWorkSheet && nCopyRow < 1 && nInsertRow < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Rows(int)", nCopyRow);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Copy()");
    m_pAxObj = m_pWorkSheet->querySubObject("Rows(int)", nInsertRow);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Insert()");
    return true;
}


bool AdvanceExcel::copyColumnThenInsert(int nCopyCol, int nInsertCol)
{
    if(!m_pWorkSheet && nCopyCol < 1 && nInsertCol < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Columns(int)", nCopyCol);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Copy()");

    m_pAxObj = m_pWorkSheet->querySubObject("Columns(int)", nInsertCol);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Insert()");

    return true;
}


bool AdvanceExcel::copyRowThenPaste(int nCopyRow, int nInsertRow)
{

    if(!m_pWorkSheet && nCopyRow < 1 && nInsertRow < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Rows(int)", nCopyRow);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Copy()");

    m_pAxObj = m_pWorkSheet->querySubObject("Rows(int)", nInsertRow);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("PasteSpecial()");
    return true;
}


bool AdvanceExcel::copyColumnThenPaste(int nCopyCol, int nInsertCol)
{
    if(!m_pWorkSheet && nCopyCol < 1 && nInsertCol < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Columns(int)", nCopyCol);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Copy()");

    m_pAxObj = m_pWorkSheet->querySubObject("Columns(int)", nInsertCol);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("PasteSpecial()");

    return true;
}


bool AdvanceExcel::copyBlockThenInsert(const QString& strCellCopy, const QString& strCellPast)
{
    if(!m_pWorkSheet) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Range(QVariant&,QVariant&)", strCellCopy);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Copy()");

    m_pAxObj = m_pWorkSheet->querySubObject("Range(QVariant&,QVariant&)", strCellPast);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Insert()");

    return true;
}

bool AdvanceExcel::copyBlockThenPaste(const QString &strCellCopy, const QString &strCellPast)
{

    if(!m_pWorkSheet) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Range(QVariant&,QVariant&)", strCellCopy);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Copy()");

    m_pAxObj = m_pWorkSheet->querySubObject("Range(QVariant&,QVariant&)", strCellPast);
    m_pAxObj->dynamicCall("Select()");
    m_pAxObj->dynamicCall("PasteSpecial()");

    return true;
}



bool AdvanceExcel::multiSelectCopy(const QString& strCellCopy, const QString& strCellPaste)
{

    //    QAxObject* worksheet_copy_after= m_pWorkSheet->querySubObject("Item( int )",5);
    //    QVariant param1= worksheet_copy_after->asVariant();
    //    m_pWorkSheet->dynamicCall("Copy (const QVariant&)",param1);




    m_pAxObj = m_pWorkSheet->querySubObject("Range(QVariant&,QVariant&)", strCellCopy);
    m_pAxObj->dynamicCall("Select()");

    m_pAxObj->dynamicCall("Copy()");

    m_pAxObj = m_pWorkSheet->querySubObject("Range(QVariant&,QVariant&)", strCellPaste);//->dynamicCall("Select()");
    m_pAxObj->dynamicCall("Paste()");
    return true;

    //VBA:
    //Range("C4,E4,G4").Select
    //Range("G4").Activate
    //Selection.Copy
    //Range("C26").Select
    //ActiveSheet.Paste
    //------
    //Range("F1").Select
    //Range(Selection, Selection.End(xlDown)).Select
    //Selection.Copy
    //Range("I29").Select
    //ActiveSheet.Paste
    //==============
    //	QAxObject* pasteRange = getRange(2, 14, 2, 14);
    //	getRange(1, 1, 1, 1);
    //	range->dynamicCall("Select");
    //	range->dynamicCall("Copy");
    //	getRange(1, 2, 1, 2);
    //		range->dynamicCall("Select");
    //	range->dynamicCall("Copy");
    ////	range->dynamicCall("Select");
    ////	range->dynamicCall("Paste");
    //	range->querySubObject("Copy(const QVariant&)", pasteRange->asVariant());

    //getRange(2, 3);
}




bool AdvanceExcel::deleteRow(int nRowNum)
{
    if(!m_pWorkSheet && nRowNum < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Rows(int)",nRowNum);
    m_pAxObj->dynamicCall("Delete()");
    return true;
}


bool AdvanceExcel::deleteColumn(int nColumnNum)
{
    if(!m_pWorkSheet && nColumnNum < 1) return false;
    m_pAxObj = m_pWorkSheet->querySubObject("Columns(int)",nColumnNum);
    m_pAxObj->dynamicCall("Delete()");
    return true;
}


bool AdvanceExcel::sumFunc(const QString &strCell, const QString &strCellResult)
{
    if(!m_pWorkSheet) return false;

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCellResult);
    QString strSum = "=SUM("+ strCell +")";
    m_pAxObj->dynamicCall("SetValue(const QString&)",strSum);
    return true;
}


bool AdvanceExcel::sumFunc(const QStringList &strCells, const QString &strCellResult)
{
    if(!m_pWorkSheet) return false;

    QString strSum = "=SUM(";
    for (int i = 0; i< strCells.size(); i++)
    {
        strSum += strCells.at(i) + ",";
    }
    strSum += ")";

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCellResult);
    m_pAxObj->dynamicCall("SetValue(const QString&)",strSum);

    return true;
}




void AdvanceExcel::setColumnWidth(int nColumn, int width)
{
    QString strColumnName;
    strColumnName.append(QChar(nColumn - 1 + 'A'));
    strColumnName.append(":");
    strColumnName.append(QChar(nColumn - 1 + 'A'));

    m_pAxObj = m_pWorkSheet->querySubObject("Columns(const QString&)", strColumnName);
    m_pAxObj->setProperty("ColumnWidth", width);
}


void AdvanceExcel::setRowHeight(int nRow, int height)
{
    QString strRowsName;
    strRowsName.append(QString::number(nRow));
    strRowsName.append(":");
    strRowsName.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Rows(const QString &)", strRowsName);
    m_pAxObj->setProperty("RowHeight", height);
}


void AdvanceExcel::setCellTextCenter(int nRow, int nColumn)
{
    QString strCell;
    strCell.append(QChar(nColumn - 1 + 'A'));
    strCell.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("HorizontalAlignment", -4108);//xlCenter
}


void AdvanceExcel::setCellTextCenter(const QString &strCell)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("HorizontalAlignment", -4108);//xlCenter
}

//上對齊(xlTop)-4160
// 下對齊(xlBottom):-4107

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

//#define ALIGNMENT_CENTER   (-4108)
//#define ALIGNMENT_LEFT     (-4131)
//#define ALIGNMENT_RIGHT    (-4152)
//#define ALIGNMENT_DEFAULT   1

void AdvanceExcel::setCellTextLeft(int nRow, int nColumn)
{
    QString strCell;
    strCell.append(QChar(nColumn - 1 + 'A'));
    strCell.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("HorizontalAlignment", -4131);//左對齊(xlLeft)
}


void AdvanceExcel::setCellTextLeft(const QString &strCell)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("HorizontalAlignment", -4131);//左對齊(xlLeft)
}


void AdvanceExcel::setCellTextRight(int nRow, int nColumn)
{
    QString strCell;
    strCell.append(QChar(nColumn - 1 + 'A'));
    strCell.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("HorizontalAlignment", -4152);//右對齊(xlRight)
}


void AdvanceExcel::setCellTextRight(const QString &strCell)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("HorizontalAlignment", -4152);//右對齊(xlRight)
}


void AdvanceExcel::setCellTextWrap(int nRow, int nColumn, bool isWrap)
{
    QString strCell;
    strCell.append(QChar(nColumn - 1 + 'A'));
    strCell.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("WrapText", isWrap);
}


void AdvanceExcel::setCellTextWrap(const QString &strCell, bool isWrap)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj->setProperty("WrapText", isWrap);
}


void AdvanceExcel::setAutoFitRow(int nRow)
{
    QString strRowsName;
    strRowsName.append(QString::number(nRow));
    strRowsName.append(":");
    strRowsName.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Rows(const QString &)", strRowsName);
    m_pAxObj->dynamicCall("AutoFit()");
}


void AdvanceExcel::setAutoFitCol(int nColumn)
{
    QString strColName;
    strColName.append(QString::number(nColumn));
    strColName.append(":");
    strColName.append(QString::number(nColumn));

    m_pAxObj = m_pWorkSheet->querySubObject("columns(const QString &)", strColName);
    m_pAxObj->dynamicCall("AutoFit()");
}


void AdvanceExcel::mergeSerialSameCellsInAColumn(int nColumn, int topRow)
{
    int a,b,c,rowsCount;
    getUsedRange(&a, &b, &rowsCount, &c);

    int aMergeStart = topRow, aMergeEnd = topRow + 1;

    QString value;
    while(aMergeEnd <= rowsCount)
    {
        value = getCellValue(aMergeStart, nColumn).toString();
        while(value == getCellValue(aMergeEnd, nColumn).toString())
        {
            clearCell(aMergeEnd, nColumn);
            aMergeEnd++;
        }
        aMergeEnd--;
        mergeCells(aMergeStart, nColumn, aMergeEnd, nColumn);

        aMergeStart = aMergeEnd + 1;
        aMergeEnd = aMergeStart + 1;
    }
}


int AdvanceExcel::getUsedRowsCount()
{
    if(!m_pWorkSheet) return 0;
    m_pAxObj = m_pWorkSheet->querySubObject("UsedRange");
    //int nTopRow = m_pAxObj->property("Row").toInt();
    m_pAxObj = m_pAxObj->querySubObject("Rows");
    int nCount = m_pAxObj->property("Count").toInt() ;
    return nCount;
}


int AdvanceExcel::getUsedColumnsCount()
{
    if(!m_pWorkSheet) return 0;
    m_pAxObj = m_pWorkSheet->querySubObject("UsedRange");

    m_pAxObj = m_pAxObj->querySubObject("Columns");
    int nCount = m_pAxObj->property("Count").toInt();
    return nCount;
}


void AdvanceExcel::getUsedRange(int* nTopLeftRow, int* nTopLeftColumn, int* nBottomRightRow, int* nBottomRightColumn)
{
    m_pAxObj = m_pWorkSheet->querySubObject("UsedRange");
    *nTopLeftRow = m_pAxObj->property("Row").toInt();   //獲取起始行
    *nTopLeftColumn = m_pAxObj->property("Column").toInt(); //獲取起始列

    QAxObject*rows = m_pAxObj->querySubObject("Rows");
    *nBottomRightRow = *nTopLeftRow + rows->property("Count").toInt() - 1;    //獲取行數

    QAxObject*columns = m_pAxObj->querySubObject("Columns");
    *nBottomRightColumn = *nTopLeftColumn + columns->property("Count").toInt() - 1;   //獲取列數
}


void AdvanceExcel::setCellFontBold(int nRow, int nColumn, bool bBold)
{
    QString strCell;
    strCell.append(QChar(nColumn - 1 + 'A'));
    strCell.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj = m_pAxObj->querySubObject("Font");
    m_pAxObj->setProperty("Bold", bBold);
}


void AdvanceExcel::setCellFontBold(const QString &strCell, bool bBold)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj = m_pAxObj->querySubObject("Font");
    m_pAxObj->setProperty("Bold", bBold);
}


void AdvanceExcel::setCellFontSize(int nRow, int nColumn, int size)
{
    QString strCell;
    strCell.append(QChar(nColumn - 1 + 'A'));
    strCell.append(QString::number(nRow));

    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj = m_pAxObj->querySubObject("Font");
    m_pAxObj->setProperty("Size", size);
}


void AdvanceExcel::setCellFontSize(const QString &strCell, int size)
{
    m_pAxObj = m_pWorkSheet->querySubObject("Range(const QString&)", strCell);
    m_pAxObj = m_pAxObj->querySubObject("Font");
    m_pAxObj->setProperty("Size", size);
}


void AdvanceExcel::save()
{
    m_pWorkBook->dynamicCall("Save()");
}



#include <QCoreApplication>
void AdvanceExcel::saveAs(const QString& strPath)
{
    //QString filepath=QFileDialog::getSaveFileName(nullptr, tr("Save orbit"),".", tr("Microsoft Office 2010 (*.xlsx)"));//獲取保存路徑
    //保存至filepath,注意一定要用QDir::toNativeSeparators將路徑中的"/"轉換爲"\",不然一定保存不了。
    //m_pWorkBook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(strPath));

}


void AdvanceExcel::close()
{    
    if(m_pExcel)
    {
        m_pExcel->dynamicCall("Close()");
        m_pExcel->dynamicCall("Quit()");//關閉excel
    }

    DEL_OBJ(m_pWorkSheet);
    DEL_OBJ(m_pWorkSheets);
    DEL_OBJ(m_pWorkBook);
    DEL_OBJ(m_pWorkBooks);

    DEL_OBJ(m_pExcel);
}



void AdvanceExcel::onAxWidgetException(int, const QString & strA, const QString & strB, const QString &strC)
{
    qDebug()<<strA<<"\n"<<strB<<"\n"<<strC;
    return;
}


在這裏插入圖片描述

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