天天看点

Qt 使用QAxObject创建一个excel1.pro添加配置2.头文件3.头文件4.实现5.调用

1.pro添加配置

QT       += axcontainer
           

2.头文件

#include <QAxObject>
           

3.头文件

void newExcel(const QString &fileName);// 新建一个excel
    void appendSheet(const QString &sheetName,int cnt);// 增加一个worksheet
    void setCellValue(int row,int column,const QString &value);// 向Excel单元格中写入数据
    void saveExcel(const QString &fileName);// 保存excel
    void freeExcel();// 释放excel

private:
    Ui::TestExcel *ui;
    QAxObject *pApplication;
    QAxObject *pWorkBooks;
    QAxObject *pWorkBook;
    QAxObject *pSheets;
    QAxObject *pSheet;
           

4.实现

// 新建一个excel
void TestExcel::newExcel(const QString &fileName)
{
    pApplication = new QAxObject("Excel.Application");
    if (pApplication == nullptr) {
        qWarning("pApplication\n");
        return;
    }
    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");
    pSheet = pSheets->querySubObject("Item(int)",1);
}

// 增加一个worksheet
void TestExcel::appendSheet(const QString &sheetName,int cnt)
{
    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);
}

// 向Excel单元格中写入数据
void TestExcel::setCellValue(int row,int column,const QString &value)
{
    QAxObject *pRange = pSheet->querySubObject("Cells(int,int)",row,column);
    pRange->dynamicCall("Value",value);
}

// 保存excel
void TestExcel::saveExcel(const QString &fileName)
{
    pWorkBook->dynamicCall("SaveAs(const QString &)",QDir::toNativeSeparators(fileName));
}

// 释放excel
void TestExcel::freeExcel()
{
    if (pApplication != nullptr) {
        pApplication->dynamicCall("Quit()");
        delete pApplication;
        pApplication = nullptr;
    }
}
           

5.调用

void TestExcel::on_writeBtn_2_clicked()
{
    QString fileName = "e:/测试.xlsx";
    newExcel(fileName);
    setCellValue(3,3,"Hello");
    setCellValue(3,6,"World");
    saveExcel(fileName);
    freeExcel();
}
           
Qt

继续阅读