同樣需要使用QT += axcontainer
同樣需要注意:新建QAXObject,完成操作后需要關(guān)閉文檔并刪除m_pWord指針,!
這樣word應(yīng)用程序會(huì)在后臺(tái)自動(dòng)退出!
class Word : public QObject explicit Word(QObject *parent = nullptr); QString m_fileName;//存入位置 QAxObject *m_pDocument;// const QString dot = "ZYLH1220本安穩(wěn)壓電源老化報(bào)告模板.dot"; void createWordDocument();//創(chuàng)建word文檔 bool insertText(QString Tag, QString text);//往標(biāo)簽處插入文字 void saveAndQuit(const QString &text);//保存文檔并退出
#include <QCoreApplication> Word::Word(QObject *parent) : QObject(parent) void Word::createWordDocument() m_pWord = new QAxWidget("Word.Application");//新建一個(gè)word應(yīng)用程序 m_pWord->setProperty("Visible", false);//不顯示窗體 QAxObject *pDocuments = m_pWord->querySubObject("Documents"); pDocuments->dynamicCall("Add(Qstring)", QCoreApplication::applicationDirPath() + "/" + dot);//模版目錄 m_pDocument = m_pWord->querySubObject("ActiveDocument");//獲取當(dāng)前激活的文檔 bool Word::insertText(QString Tag, QString text) if (m_pDocument->isNull()) return false;//首先判斷有沒有獲取當(dāng)前激活的文檔,,沒有則返回失敗 QAxObject *pBookMarkCode = m_pDocument->querySubObject("Bookmarks(QVariant)", Tag);//獲取指定標(biāo)簽 pBookMarkCode->dynamicCall("Start");//選擇該指定標(biāo)簽 pBookMarkCode->querySubObject("Range")->setProperty("Text", text);//往標(biāo)簽處插入文字 void Word::saveAndQuit(const QString &text) m_pDocument->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(text));//“/”換成“\”,;否則在windows下保存不成功 m_pDocument->dynamicCall("Close()");//關(guān)閉 m_pWord->dynamicCall("Quit()");//退出
以上代碼基于對(duì)此文的改進(jìn),!
原文:提示沒有該屬性,正確的應(yīng)該是start,;
pBookMarkCode->dynamicCall("Selection");//選擇該指定標(biāo)簽
Quit的調(diào)用主題應(yīng)該是m_pWord,;
最后delete;
Qt 對(duì)word的基本簡(jiǎn)單操作_小鳥cc的博客-CSDN博客_qt word
|