Qt 使用QAxObject创建一个excel

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();
}
发布了257 篇原创文章 · 获赞 22 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_24127015/article/details/104614315