Qt随手笔记(五)vs+qt使用QAxObject读取word(内容、句子、段落、表格)

一、配置环境
1、配置环境
本案例使用的vs2019、qt5.12.10和word2016
a) 使用vs2019新建一个QtWidgetsApplication项目
b)加载头文件和库
打开项目的属性
在这里插入图片描述

添加头文件目录
目录为qt安装路径中的Active
在这里插入图片描述
添加库目录
目录为qt安装路径下的lib
在这里插入图片描述
添加附加依赖项
Qt5AxContainerd.lib;Qt5Axbased.lib
在这里插入图片描述
二、设计ui界面
添加一个button按钮,objectName为pushButton
和一个textEdit控件,objectName为textEdit
在这里插入图片描述
点击保存
再点击窗体->查看代码
在这里插入图片描述
在弹出的窗口中,点击保存
在这里插入图片描述
然后关闭ui界面
右击项目,重新扫描解决方案,重新生成;在这里插入图片描述
三、项目代码如下
头文件:

#pragma once
#pragma execution_character_set("utf-8")

#include <QtWidgets/QMainWindow>
#include "ui_QtWidgetsApplication1.h"

//****************************************
//新添加头文件
#include <qfiledialog.h>
#include <QAxObject>
//****************************************



class QtWidgetsApplication1 : public QMainWindow
{
    Q_OBJECT

public:
    QtWidgetsApplication1(QWidget *parent = Q_NULLPTR);
    ~QtWidgetsApplication1();//添加析构函数
private:
    Ui::QtWidgetsApplication1Class ui;


//************************************************************
//以下为新添加
public slots:
    void pushButton();//添加槽函数

public:
    void OpenWord(QString& filename);     //打开word文档

    QString getLine(int start, int end);  //读取文档中第几个字到第几个字
    QString getAllText();                 //直接获取word中所有文本

    
    void getSentences();    //获取word中的所有句子
    void getParagraphs();   //获取word中的所有段落
    void readTables();      //获取word中所有表格

private:
    QAxObject* m_word;
    QAxObject* m_document;
    QAxObject* m_doc;

};

cpp文件

#include "QtWidgetsApplication1.h"




QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    //******************************************************************
    //添加按钮的信号与槽函数
    connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(pushButton()));
   
    //******************************************************************
    //新添加
    m_word = new QAxObject("Word.Application");       //启动word应用进程
    m_document = m_word->querySubObject("Documents"); //获取Documents对象
   //*******************************************************************
}

//******************************************************
 //新添加(析构函数)
QtWidgetsApplication1:: ~QtWidgetsApplication1()
{
   
    m_word->dynamicCall("Quit()");//关闭word进程

    delete m_doc;
    m_doc = nullptr;

    delete m_document;
    m_document = nullptr;

    delete m_word;
    m_word = nullptr;
}


//******************************************************
//槽函数
void QtWidgetsApplication1::pushButton()
{
    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::ExistingFile);
    dialog.setViewMode(QFileDialog::Detail);
    dialog.setOption(QFileDialog::ReadOnly, true);
    dialog.setWindowTitle(QString("QAXwidget操作文件"));
    dialog.setDirectory(QString("./"));
    dialog.setNameFilter(QString("所有文件(*.*);;excel(*.xlsx);;word(*.docx *.doc);;pdf(*.pdf)"));
    if (dialog.exec())
    {
        //根据文件后缀打开
        QStringList files = dialog.selectedFiles();
        for (auto filename : files)
        {
            if (filename.endsWith(".xlsx"))
            {
                //this->OpenExcel(filename);
            }
            else if (filename.endsWith(".docx") || filename.endsWith(".doc"))
            {
                this->OpenWord(filename);
            }

            /*if (filename.endsWith(".docx") || filename.endsWith(".doc"))
            {
                this->OpenWord(filename);
            }*/
        }
    }
}

//打开要读取的word文档
void QtWidgetsApplication1::OpenWord(QString& filename)
{
   

    m_document->dynamicCall("Open(const QString&)", filename);//打开选择的word文档
    m_word->setProperty("Visible", QVariant(false));          //不显示word窗口
    m_doc = m_word->querySubObject("ActiveDocument");         //获取当前工作簿(Documents object)

    //1
    //QString s = getLine(0, 20);//读取文档中第几个字到第几个字
    //ui.textEdit->setText(s);   //在textEdit中显示
    //ui.textEdit->append(s);    //已追加的方式在text中显示

    //2
    QString alltext = getAllText();  //直接获取word中所有文本
    ui.textEdit->setText(alltext);

    //3
    //readTables();    //获取word中所有表格

    //4
    //getSentences();  //获取word中的所有句子(以句号或回车标志为一句)
 
    //5
    //getParagraphs(); //获取word中的所有段落(以回车标志为一段)


    //关闭当前打开的word文档
    m_word->setProperty("Visible", QVariant(false));   //不显示word窗口
    m_document->dynamicCall("Close()");
    m_word->setProperty("Visible", QVariant(false));   //不显示word窗口


}

//获取第start个字到第end个字
QString QtWidgetsApplication1::getLine(int start, int end)
{
    QString text;
    if (NULL == m_doc)
        return text;

    QVariantList params;
    params << start << end;
    QAxObject* pRange = m_doc->querySubObject("Range(QVariant&, QVariant&)", params);
    text = pRange->property("Text").toString();
    delete pRange;
    pRange = NULL;
    return text;
}

//直接获取所有文字
QString QtWidgetsApplication1::getAllText()
{
    QString text;
    if (NULL == m_doc)
        return text;

    QAxObject* pRange = m_doc->querySubObject("Range()");

    if (NULL != pRange)
    {
        text = pRange->property("Text").toString();
        delete pRange; 
        pRange = NULL;
    }
    return text;
}

//获取word中所有表格
void QtWidgetsApplication1::readTables()
{
   
    if (NULL == m_doc) return;
    QAxObject* tables = m_doc->querySubObject("Tables"); //获取所有表格

    int tablecount = -1;
    if (NULL != tables)
    {
        tablecount = tables->dynamicCall("Count").toInt(); //获取表格个数
        delete tables;
        tables = NULL;
    }
    for (int i = 1; i <= tablecount; i++)
    {
        
        QAxObject* table = m_doc->querySubObject("Tables(int)", i); //获取第i个表格
        if (NULL == table) continue;
        QString title = table->property("Text").toString();;//获取表格的标题
        //ui.textEdit->append("表格标题" + title);

        int row = table->querySubObject("Rows")->dynamicCall("Count").toInt(); //获取行数
        int col = table->querySubObject("Columns")->dynamicCall("Count").toInt();//获取列数
        //ui.textEdit->append("行数" + QString::number(row));
        //ui.textEdit->append("列数" + QString::number(col));

        QAxBase::PropertyBag p = table->propertyBag();
        
        for (int j = 1; j <= row; j++)
        {
            for (int z = 1; z <= col; z++)
            {
                //获取表格中第j行第在列的数据
                QAxObject* cell = table->querySubObject("Cell(int,int)", j, z); 
                if (NULL == cell) continue;
                QString sp = cell->querySubObject("Range")->property("Text").toString();
     
                ui.textEdit->append(sp);

                delete cell;
                cell = NULL;
            }

        }
        delete table;
        table = NULL;
    }

    delete tables;
    tables = NULL;
  
}

//获取word中的所有句子
void QtWidgetsApplication1::getSentences()
{
    QAxObject* sentences = m_doc->querySubObject("Sentences");//获取所有的句子
    int count = sentences->dynamicCall("count").toInt();//获取句子的数量

    for (int i = 1; i <= count; i++)
    {
        QAxObject* sentence = sentences->querySubObject("Item(int)", i);//获取第i句
        QString sp = sentence->property("Text").toString();//获取第i句的文字

        ui.textEdit->append(sp);
        //ui.textEdit->append("-----------------");

        delete sentence;
        sentence = nullptr;
    }

    delete sentences;
    sentences = nullptr;
}

//获取word中的所有段落
void QtWidgetsApplication1::getParagraphs()
{
    QAxObject* paragraphs = m_doc->querySubObject("Paragraphs");//获取word中所有段
    int count = paragraphs->dynamicCall("count").toInt();//获取word中段落的数量

    for (int i = 1; i <= count; i++)
    {
        //获取每段话的文字
        QAxObject* par1 = paragraphs->querySubObject("Item(int)", i);//选择第i段
        QAxObject* range = par1->querySubObject("range");
        QString sp = range->property("Text").toString();

        ui.textEdit->append(sp);
        //ui.textEdit->append("-----------------");

        delete par1;
        par1 = nullptr;

        delete range;
        range = nullptr;
    }
    delete paragraphs;
    paragraphs = nullptr;
}

注意:因为关闭word进程的语句放在了析构函数中。
所以关闭时要点击对话框的×号,否则word进程仍然在后台运行,需要调用任务管理器关闭。在这里插入图片描述

  • 4
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
可以使用 QAxObject 类来读取 Excel 文件中的数据,并将其显示在 Qt 的 TableWidget 控件中。以下是一个简单的示例代码: ```cpp #include <QAxObject> #include <QTableWidget> void readExcelFile(QString fileName, QTableWidget *tableWidget) { QAxObject excel("Excel.Application", 0); QAxObject *workbooks = excel.querySubObject("Workbooks"); QAxObject *workbook = workbooks->querySubObject("Open(const QString&)", fileName); QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1); QAxObject *usedrange = worksheet->querySubObject("UsedRange"); QAxObject *rows = usedrange->querySubObject("Rows"); QAxObject *columns = usedrange->querySubObject("Columns"); int rowCount = rows->property("Count").toInt(); int columnCount = columns->property("Count").toInt(); tableWidget->setRowCount(rowCount); tableWidget->setColumnCount(columnCount); for (int i = 1; i <= rowCount; i++) { for (int j = 1; j <= columnCount; j++) { QAxObject *cell = worksheet->querySubObject("Cells(int,int)", i, j); QVariant value = cell->dynamicCall("Value()"); QString strValue = value.toString(); tableWidget->setItem(i - 1, j - 1, new QTableWidgetItem(strValue)); delete cell; } } delete columns; delete rows; delete usedrange; delete worksheet; workbook->dynamicCall("Close()"); delete workbook; delete workbooks; excel.dynamicCall("Quit()"); } ``` 调用示例: ```cpp QTableWidget *tableWidget = new QTableWidget(this); readExcelFile("test.xlsx", tableWidget); ``` 其中,"test.xlsx" 为 Excel 文件名,tableWidget 为要显示数据的 TableWidget 控件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值