QAxWidget 打开word、pdf、excel、ppt

QAxWidget 打开word、pdf、excel、ppt
使用QAxWidget打开word,pdf,excel,其中word高亮关键字。
打开txt并高亮关键字见另一文。添加链接描述
PPT操作文字颜色见另一文。添加链接描述

目前存在的问题:
1.excel打开在我电脑上时好时坏,有时可以直接打开并内嵌,有时excel.exe一闪而过,似乎是进程内有问题调起来又崩溃消失了,会报错CoCreateInstance failure (没有注册类),暂时未解决。
2.ppt只能直接打开,无法内嵌进窗口。
3.word开启后进程可以正常关闭,excel和ppt暂无法关闭。

    //打开指定文件,高亮关键字,只有word和txt实现高亮关键字
    void openFile(QString strFileName, QStringList& strKeys)
    {
            closeFiles();
            if (strFileName.endsWith(".docx") || strFileName.endsWith(".doc"))
            {
                openWord(strFileName, strKeys);
            }
            else if (strFileName.endsWith(".xlsx") || strFileName.endsWith(".xls"))
            {
                openExcel(strFileName, strKeys);
            }
            else if (strFileName.endsWith(".pptx") || strFileName.endsWith(".ppt"))
            {
                openPpt(strFileName, strKeys);
            }
            else if (strFileName.endsWith(".pdf"))
            {
                openPdf(strFileName, strKeys);
            }
            else if (strFileName.endsWith(".txt"))
            {
                openTxt(strFileName, strKeys);
            }
    }

    //删除进程,保证反复切换和打开各种文档时只有一个进程
    void closeFiles()
    {
        if (this->m_pfileView != nullptr)
        {
            //这样写可以真正关掉winword进程,但是如果开着其他的进程,都会被杀掉,而不是进杀掉qt打开的这个
            /*QProcess process;
            QString strCmd = "taskkill /im winword.exe /f";
            process.execute(strCmd);
            strCmd = "taskkill /im EXCEL.exe /f";
            process.execute(strCmd);
            strCmd = "taskkill /im POWERPNT.exe /f";
            process.execute(strCmd);
             strCmd = "taskkill /im AcroRd32.exe /f";
            process.execute(strCmd);
            process.close();
            m_pfileView->close();
            m_pfileView->clear();
            delete m_pfileView;
            m_pfileView = nullptr;*/
        if (m_strFileName.endsWith(".docx") || m_strFileName.endsWith(".doc"))
        {
            QAxObject *app = m_pfileView->querySubObject("Application");
            if (app != nullptr)
            {
                m_pfileView->dynamicCall("Close(boolean)", false);
                m_pfileView->close();
                m_pfileView->clear();
                app->dynamicCall("Quit ()");
                   delete app;
                app = NULL;
            }
        }
        else if(m_strFileName.endsWith(".xlsx") || m_strFileName.endsWith(".xls"))
        {
            //可能无法关闭
            m_pfileView->dynamicCall("Quit()");
        }
        else if(m_strFileName.endsWith(".pptx") || m_strFileName.endsWith(".ppt"))
        {
            //可能无法关闭
            m_pfileView->dynamicCall("Quit()");
        }
        
        QFile fileTemp(m_strSaveFileName);
        fileTemp.remove();

        if (m_pPlainTextEdit != nullptr)
        {
            delete m_pPlainTextEdit;
            m_pPlainTextEdit = nullptr;
        }
    }

操作word,实现高亮关键字,实际上是把关键字找出来标记后保存为临时文件。

    // 高亮操作函数
    // dirName:是待检查文件的路径;keyWords:是要查找的关键字(查找的关键字可能是多个)
    bool highLightKeyWordsinWordFile(QString dirName, QStringList keyWords)
    {
        int lastSeparatorIndex = dirName.lastIndexOf(QDir::separator());
        m_strSaveFileName = QApplication::applicationDirPath() + "/" + dirName.mid(lastSeparatorIndex + 1);  // 另存为的路径

        QAxWidget wordApplication("Word.Application");
        QAxObject *documents = wordApplication.querySubObject("Documents");
        documents->dynamicCall("Open(const QString&)", dirName);
        wordApplication.setProperty("Visible", QVariant(false));
        QAxObject* m_doc = wordApplication.querySubObject("ActiveDocument");    // 获取当前工作簿
        QAxObject* pRange = m_doc->querySubObject("Content()");

        if (NULL != pRange)
        {
            // 查找关键字
            QAxObject *pFind = pRange->querySubObject("Find()");
            QStringList keyWordsPosition;
            if (NULL != pFind)
            {
                pFind->dynamicCall("ClearFormatting()");
                pFind->setProperty("Format", true);
                pFind->setProperty("MatchCase", false);
                pFind->setProperty("MatchWholeWord", false);
                pFind->setProperty("MatchByte", true);
                pFind->setProperty("MatchWildcards", false);
                pFind->setProperty("MatchSoundsLike", false);
                pFind->setProperty("MatchAllWordForms", false);

                for (int i = 0; i < keyWords.size(); ++i) {
                    // 找到关键字所在的位置,得到一个position,将position添加到keyWordsPosition中。
                    QString keyWord = keyWords.at(i);
                    QStringList position = findKeyWordsPosition(pRange->property("Text").toString(), keyWord);
                    if (!position.contains("")) {
                        keyWordsPosition << position;

                        pFind->setProperty("Text", keyWord);
                        pFind->dynamicCall("Execute()");
                        while (pFind->property("Found").toBool())
                        {
                            bool isHighlight = pFind->parent()->setProperty("HighlightColorIndex", "wdYellow");
                            pFind->dynamicCall("Execute()");

                            if (!isHighlight)
                            {
                                delete pFind;
                                pFind = NULL;
                                delete pRange;
                                pRange = NULL;
                                m_doc->dynamicCall("Close(boolean)", true);
                                wordApplication.dynamicCall("Quit ()");
                                delete m_doc;
                                m_doc = NULL;
                                return false;
                            }
                        }
                    }
                }
            }
            if (keyWordsPosition.size() >= 1) {
                QString fileName = dirName.mid(lastSeparatorIndex + 1);
                QString filePath = dirName.mid(0, lastSeparatorIndex + 1);

                m_doc->dynamicCall("SaveAs(const QString)", m_strSaveFileName);
            }
            delete pFind;
            pFind = NULL;
            delete pRange;
            pRange = NULL;
            m_doc->dynamicCall("Close(Boolean)", true);
            m_doc->dynamicCall("Quit()");
            delete m_doc;
            m_doc = NULL;
            return true;
        }
        return true;
    }

    QStringList findKeyWordsPosition(QString fileContent, QString keyWord)
    {
        QStringList resList;
        if (fileContent.contains(keyWord)) {
            qDebug() << QObject::tr("包含子字符串 : %1").arg(keyWord);

            int startIndex = 0;
            //        int count = 0;
            int keyWordsLen = keyWord.length();
            QRegExp rx(QObject::tr("[,。:\r]?([^,。:\r]*(%1)[^,。:\r]*)[,。:\r]?").arg(keyWord));

            while ((startIndex = rx.indexIn(fileContent, startIndex)) != -1) {
                QString resStr = rx.cap(1).mid(0);   // 提取子字符串所在的语句
                if (resStr.contains("\r"))
                    resStr.replace("\r", "");
                resList << resStr;

                // 找到子字符串
                int findIndex = fileContent.indexOf(keyWord, startIndex);
                //            qDebug() << QObject::tr("keyWords 出现的位置 : %1").arg(findIndex);
                startIndex = findIndex + keyWordsLen;
                //            qDebug() << QObject::tr("keyWords 出现的次数 : %1").arg(++count);
                qDebug() << "\n";
            }

            return resList;
        }
        return resList << "";
    }
    
    void openWord(const QString & str, QStringList& strKeyList)
    {
        highLightKeyWordsinWordFile(m_strFileName, strKeyList);
        m_pfileView = new QAxWidget("Word.Application", ui.m_pFileWidget);
        if (m_pfileView == nullptr)
        {
            return;
        }
        m_pfileView->resize(width(), ui.m_pFileWidget->height());

        m_pfileView->dynamicCall("SetVisible (bool Visible)", "false");//不显示窗体
        m_pfileView->setFocusPolicy(Qt::StrongFocus);
        QAxObject *documents = m_pfileView->querySubObject("Documents");
        m_pfileView->setControl(str);
        documents->setProperty("DisplayAlerts", false);
        m_pfileView->setProperty("DisplayAlerts", false);
        m_pfileView->setProperty("DisplayHorizontalScrollBar", true); // 显示滚动条  

        //本来是想把文本的显示百分比调整下,但是并不生效。
        /*QAxObject* m_doc = m_pfileView->querySubObject("ActiveWindow");    // 获取当前工作簿
        QAxObject* pActivePane = m_doc->querySubObject("ActivePane");
        QAxObject* pView = pActivePane->querySubObject("View");
        QAxObject* pZoom = pView->querySubObject("Zoom");
        pZoom->setProperty("Percentage", 150);*/

        //等待一会,不然显示出来会特别小
        wait(500);

        m_pfileView->show();
        m_pfileView->raise();
    }


打开excel

    void openExcel(const QString & str, QStringList& strKeyList)
    {
        m_pfileView = new QAxWidget("Excel.Application", ui.m_pFileWidget);
        if (m_pfileView == nullptr)
        {
            return;
        }
        QFileInfo info(str);
        if (!info.exists())
        {
            qDebug() << "file.exists not " << "\n";
        }
        m_pfileView->setControl(QDir::toNativeSeparators(info.absoluteFilePath()));
        m_pfileView->dynamicCall("SetVisible (bool Visible)", false);
        m_pfileView->resize(width(), ui.m_pFileWidget->height());
        wait(500);
        m_pfileView->show();
        m_pfileView->raise();
    }


打开pdf

    void openPdf(const QString & str, QStringList& strKeyList)
    {
        m_pfileView = new QAxWidget(ui.m_pFileWidget);
        if (m_pfileView == nullptr)
        {
            return;
        }
        if (!m_pfileView->setControl("Adobe PDF Reader"))
        {
            return;
        }

        m_pfileView->dynamicCall("LoadFile(const QString&)", str);
        m_pfileView->dynamicCall("SetVisible (bool Visible)", "false");
        m_pfileView->setProperty("DisplayAlerts", false);
        m_pfileView->setProperty("DisplayScrollBars", true); // 显示滚动条  
        m_pfileView->resize(width(), ui.m_pFileWidget->height());

        m_pfileView->show();
        m_pfileView->raise();
    }


打开ppt

    void openPpt(const QString & str, QStringList& strKeyList)
    {
        m_pfileView = new QAxWidget("Powerpoint.Application",ui.m_pFileWidget);
        if (m_pfileView == nullptr)
        {
            return;
        }
        QFileInfo info(str);
        if (!info.exists())
        {
            qDebug() << "file.exists not " << "\n";
        }
        QAxObject *presentations = m_pfileView->querySubObject("Presentations");
        presentations->dynamicCall("Open(QString)", str); 
        m_pfileView->dynamicCall("SetVisible (bool Visible)", "false");
        m_pfileView->resize(width(), ui.m_pFileWidget->height());

        wait(500);
        m_pfileView->show();
        m_pfileView->raise();
    }
————————————————
版权声明:本文为CSDN博主「Willow 」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43554422/article/details/113601506

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在使用Qt编程时,可以通过QAxWidget控件打开并操作Microsoft Word文档。首先需要在Qt项目中添加QAxWidget控件,并在代码中使用QAxWidget打开一个Word对象。 具体实现步骤如下: 1.在Qt项目中添加QAxWidget控件。 可以通过Qt设计器的控件面板找到QAxWidget控件并拖动到主窗口中,也可以在代码中使用以下代码添加: QAxWidget *word = new QAxWidget("Word.Application", this); 2.在代码中使用QAxWidget打开Word对象。 可以在Qt的Init方法中使用以下代码打开Word对象: word->setControl("Word.Application"); 3.打开Word文档。 在打开已有文档时,可以使用以下代码: word->setProperty("Visible", true); word->setProperty("DisplayAlerts", false); word->dynamicCall("SetWindowState(int)", 0); word->setProperty("Visible", true); word->setProperty("DisplayAlerts", false); word->dynamicCall("SetWindowState(int)", 0); word->setProperty("Caption", "test"); word->dynamicCall("Open(const QString&)", "文件路径"); 4.操作Word文档。 通过QAxWidget控件,可以操作打开Word文档。例如在Word文档中添加文字,可以使用以下代码: QAxObject * activeDocument = word->querySubObject("ActiveDocument"); QAxObject * activeRange = activeDocument->querySubObject("Range()"); activeRange->dynamicCall("InsertAfter(QString)", "Hello World!"); 以上便是通过QAxWidget控件打开并操作Word文档的基本步骤。在实际应用中,可以根据需要进行相应调整和扩展,完成更为复杂的文档处理功能。 ### 回答2: QAxWidget是一个Qt类,可以用来在Qt应用程序中嵌入ActiveX控件,实现与外部应用程序的通信和交互。打开Word就可以通过QAxWidgetWord的COM组件进行通信。 首先,在Qt应用程序中使用QAxWidget类实例化一个QWidget对象,并将其设置为QAxWidget的父对象。接着,通过QAxWidget的setControl函数设置要加载的ActiveX控件的CLSID(Class ID),这里需要设置为Word的CLSID: ```cpp QAxWidget * word = new QAxWidget(this); word->setControl("Word.Application"); ``` 接下来,可以使用QAxObject类操作Word中的文档,通过QAxWidget的querySubObject方法获取Word中的Document对象,再使用QAxObject类打开指定的Word文档: ```cpp QAxObject* documents = word->querySubObject("Documents"); QAxObject* document = documents->querySubObject("Open(const QString&)", filePath); ``` 其中,filePath是要打开Word文档的绝对路径。 打开Word文档后,就可以使用QAxObject的各种方法和属性对文档进行操作,例如获取文档内容、进行文本替换、保存文档等: ```cpp QAxObject* range = document->querySubObject("Range"); QString text = range->dynamicCall("Text()").toString(); range->dynamicCall("Find(QString, QVariant, QVariant)", "Hello", 2, 1); range->dynamicCall("Text(QString)", "World"); document->dynamicCall("Save()"); ``` 最后,可以通过QAxWidget的dynamicCall函数执行Word的Quit方法关闭Word应用程序: ```cpp word->dynamicCall("Quit()"); ``` 完整的示例代码如下: ```cpp #include <QApplication> #include <QAxWidget> #include <QAxObject> int main(int argc, char *argv[]) { QApplication a(argc, argv); QAxWidget * word = new QAxWidget(); word->setControl("Word.Application"); QString filePath = "C:\\test.docx"; QAxObject* documents = word->querySubObject("Documents"); QAxObject* document = documents->querySubObject("Open(const QString&)", filePath); QAxObject* range = document->querySubObject("Range"); QString text = range->dynamicCall("Text()").toString(); range->dynamicCall("Find(QString, QVariant, QVariant)", "Hello", 2, 1); range->dynamicCall("Text(QString)", "World"); document->dynamicCall("Save()"); word->dynamicCall("Quit()"); delete word; return a.exec(); } ``` 以上就是使用QAxWidget打开Word的简要过程,通过QAxWidget和QAxObject的组合,可以实现与其他应用程序的交互,为Qt应用程序增加更多的功能和灵活性。 ### 回答3: QAxWidget是Qt提供的一种操作ActiveX控件的方法,可以用来打开Office软件,如WordExcel等。 要打开Word,需要先获取到Word的COM组件的ID。以Office 2016为例,Word的ID是: ``` {000209FF-0000-0000-C000-000000000046} ``` 在打开Word之前,需要先初始化QAxWidget,并设置要获取的组件的ID: ``` QAxWidget* pWidget = new QAxWidget; pWidget->setControl("{000209FF-0000-0000-C000-000000000046}"); ``` 接下来,就可以调用QAxWidget提供的方法来打开Word了。 首先,需要使用QAxWidget的dynamicCall方法调用Documents属性,获取到Word的Document对象: ``` QAxObject* documents = pWidget->querySubObject("Documents"); QAxObject* document = documents->querySubObject("Add()"); ``` 然后,可以调用Document对象的Open方法,打开指定的Word文档: ``` document->dynamicCall("Open(const QString&)", "file.docx"); ``` 最后,还需要调用Application对象的Visible属性,将Word设置为可见状态: ``` QAxObject* application = pWidget->querySubObject("Application"); application->setProperty("Visible", true); ``` 完整代码如下: ``` #include <QApplication> #include <QAxWidget> #include <QAxObject> int main(int argc, char *argv[]) { QApplication a(argc, argv); QAxWidget* pWidget = new QAxWidget; pWidget->setControl("{000209FF-0000-0000-C000-000000000046}"); QAxObject* documents = pWidget->querySubObject("Documents"); QAxObject* document = documents->querySubObject("Add()"); document->dynamicCall("Open(const QString&)", "file.docx"); QAxObject* application = pWidget->querySubObject("Application"); application->setProperty("Visible", true); return a.exec(); } ``` 需要注意的是,打开Word时需要提前安装相应的Office套件,并且需要将其注册到系统中。否则,程序会运行失败。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值