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();
    }
————————————————
版权声明:本文为优快云博主「Willow 」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_43554422/article/details/113601506

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值