Qt操作Excel文件,附完整工程

博主因项目需求,在Qt下进行Excel操作,经查找资料后已满足项目需求。分享了接口方法、测试代码、测试结果及详细代码,测试显示可按行写入字符串、增加和重命名sheet,还给出了完整工程下载链接,开发环境为win7+Qt 5.9。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近因项目需要,需将Qt工具测试到的数据通过Excel文件存储,在Qt下以前没弄过对Excel的操作,网上铺天盖地的一顿好找,终于,皇天不负有心人,Excel方面已经能满足项目需求了,现将代码整理,方便坛友与自己后续使用。。。

接口方法

截图如下:
其中导入到数据库还需完善,其它功能都测试通过,今天实在有点乏了!
在这里插入图片描述

测试代码

创建或者打开一个Excel文件,然后在新行写入字符串!
在这里插入图片描述

测试结果

结果显示可以按行累加写入字符串,可以增加sheet,也可以对sheet重命名!
在这里插入图片描述

详细代码

widget.h文件

#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QAxObject>
#include <QDebug>

namespace Ui {
    class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
private:
    Ui::Widget *ui;
    QAxObject* m_pApplication;
    QAxObject* m_pWorkBooks;
    QAxObject* m_pWorkBook;
    QAxObject* m_pSheets;
    QAxObject* m_pSheet;
    int m_totalRowCnt;
public:
    void newCreateExl(const QString &fileName); //1.新建一个Excel
    void appendSheet(const QString &sheetName); //2.增加1个Worksheet
    void setCellVal(int row, int column, \
                        const QString &val);    //3.向Excel单元格中写入数据
    void saveExl(const QString &fileName);      //4.保存Excel
    void closeExl(const QString &fileName);     //5.关闭Excel
    void freeExl();                             //6.释放Excel
    void setSheetName(int itemIndex, \
                     const QString &sheetName); //7.设置sheet名称
    int  getRowCount(void);         //得到行数
    void openFile(QString strFile); //打开excel文件
    void importExlToDbs(void);      //导入到数据库
};
#endif 

widget.c文件代码

#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QVariant>
#include <QFile>
#include <QDir>

QString pathName = "E:/last.xlsx";

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_pApplication = NULL;
    m_pWorkBooks = NULL;
    m_pWorkBook = NULL;
    m_pSheets = NULL;
    m_pSheet = NULL;

#if 1
    newCreateExl(pathName);         //根据路径文件名创建文件,或者打开一个存在的文件
    int curLine = getRowCount()+1;  //得到文件已经存在的最大行数
    setCellVal(curLine, 1, QString("Hello excel!"));//写入新的一行
    saveExl(pathName);              //保存excel
    curLine = getRowCount()+1;      //得到新行
    setCellVal(curLine, 1, QString("This is excel test!"));//再写入一行
    //setSheetName(1, QString("new-name"));//更改Excel sheet名称
    //appendSheet(QString("新的sheet"));   //增加一个sheet
#else
    //获取Excel文件
    QString strFile = QFileDialog::getOpenFileName(this,\
                       QStringLiteral("选择Exl文件"),"",tr("Exel file(*.xls *.xlsx *.xlsm)"));
    if (strFile.isEmpty()){
        qDebug("File is empty!\n");
        return;
    }
    qDebug() << strFile;
    openFile(strFile);
#endif
}

Widget::~Widget()
{
    delete ui;
    saveExl(pathName);
    closeExl(pathName);
    freeExl();
}

void Widget::saveExl(const QString &fileName)
{
    if(m_pWorkBook != NULL) {
        m_pWorkBook->dynamicCall("SaveAs(const QString &)", QDir::toNativeSeparators(fileName));
    }
}

void Widget::closeExl(const QString &fileName)
{
    if(m_pWorkBook != NULL) {
        m_pWorkBook->dynamicCall("Close(const QString &)", QDir::toNativeSeparators(fileName));
    }
}

void Widget::freeExl()
{
    if (m_pApplication != NULL) {
        m_pApplication->dynamicCall("Quit()");
        delete m_pApplication;
        m_pApplication = NULL;
    }
}

void Widget::newCreateExl(const QString &fileName)
{
    m_pApplication = new QAxObject(this);
    m_pApplication->setControl("Excel.Application");//连接Exl控件
    m_pApplication->dynamicCall("SetVisible(bool)", false);//false不显示窗体
    m_pApplication->setProperty("DisplayAlerts", false);//不显示任何警告信息。
    m_pWorkBooks = m_pApplication->querySubObject("Workbooks");

    QFile file(fileName);
    if (file.exists()){
        qDebug("%s file exists\n", fileName.toStdString().c_str());
        m_pWorkBook = m_pWorkBooks->querySubObject("Open(const QString &)", fileName);
    }
    else {
        qDebug("%s file not exists\n", fileName.toStdString().c_str());
        m_pWorkBooks->dynamicCall("Add");
        m_pWorkBook = m_pApplication->querySubObject("ActiveWorkBook");
    }
    m_pSheets = m_pWorkBook->querySubObject("Sheets");
    m_pSheet = m_pSheets->querySubObject("Item(int)", 1);
}

void Widget::appendSheet(const QString &sheetName)
{
    int nCount = m_pSheets->property("Count").toInt();
    QAxObject *pLastSheet = m_pSheets->querySubObject("Item(int)", nCount);
    m_pSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());
    m_pSheet = m_pSheets->querySubObject("Item(int)", nCount);
    pLastSheet->dynamicCall("Move(QVariant)", m_pSheet->asVariant());
    m_pSheet->setProperty("Name", sheetName);
}

int Widget::getRowCount(void)
{
    QAxObject* range = m_pSheet->querySubObject("UsedRange"); //获取该sheet的使用范围对象
    QVariant var = range->dynamicCall("Value");
    delete range;
    QVariantList varRows = var.toList();  //得到表格中的所有数据
    if(varRows.isEmpty()){
        m_totalRowCnt = 0;
        qDebug("varRows is empty\n");
        return 0;
    }
    m_totalRowCnt = varRows.size();
    qDebug("rowCount:%d\n", m_totalRowCnt);
    return m_totalRowCnt;
}

void Widget::setCellVal(int row, int column, const QString &value)
{
    row = (row < 1)? 1 : row;
    column = (column < 1)? 1 : column;
    QAxObject *pRange = m_pSheet->querySubObject("Cells(int,int)", row, column);
    pRange->dynamicCall("Value", value);
}

void Widget::setSheetName(int itemIndex, const QString &sheetName)
{
    int nCount = m_pSheets->property("Count").toInt();
    if(itemIndex <= nCount) {
        QAxObject *pCurSheet = m_pSheets->querySubObject("Item(int)", itemIndex);
        pCurSheet->setProperty("Name", sheetName);
    }
}

完整工程地址

因文档无法将有些文件全部贴出来,需要完整工程的朋友可通过如下链接下载,我所用的开发环境是win7+Qt 5.9,
链接:https://download.youkuaiyun.com/download/maodewen11/13287709

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东皇※太一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值