(注:涉及QAxWidget、QAxObject類,需要在.pro文件中加入 CONFIG += qaxcontainer)
Word操作接口獲取途徑:
-
Microsoft Office的所有接口手冊: https://docs.microsoft.com/en-us/office/vba/api/overview/word
-
利用QAxWidget、QAxObject可以得到對應對象的手冊:返回值類型爲QString,字符串內容爲HTML的文本格式,可以將該字符串儲存爲文件,或者用QTextBrowser之類的控件展示出來。
常用方法:
(注:方法1、2使用方式相同,使用時根據返回值類型選擇對應方法)
- 啓動應用方法
- QAxWidget::QAxWidget ( const QString & c, QWidget * parent = 0, Qt::WindowFlags f = 0 ) —— 創建QAxWidget,並初始化ActiveX控件c
- setControl(const QString &) —— 初始化COM對象
//下面三行代碼可以實現打開a.docx文件
pWord = new QAxWidget("Word.Application",this);//初始化
pDocuments = pWord->querySubObject("Documents");//獲取到所有已經打開的word文件集合
pFileA = pDocuments->dynamicCall("open(QString)",“a.docx” );//打開a.docx文件,後續需要對a.docx進行的讀寫操作都要通過pFileA進行
//下面一行代碼可以實現打開a.docx文件
pWord->setControl(“a.docx”)//操作成功後直接打開a.docx文件,後續需要對文件進行的讀寫操作直接通過pWord進行,等同於上面代碼中的pFileA
- QAxObject* querySubObject(name,args…)
- 用於獲取對象的名稱爲name屬性(property)
- 用於直接調用對象的name方法(method)
- 返回值類型仍然爲QAxObject*
例如獲取範圍(pRange)內的第三個段落(pParagraph3)可以有下面兩種寫法:
//下面兩段代碼效果一樣
pParagraph3 = pRange->querySubObject("Paragraphs(3)");
pParagraph3 = pRange->querySubObject("Paragraphs(int)", 3);
- QVariant dynamicCall(name,args…)
- 用於獲取對象的名稱爲name屬性(property)
- 用於直接調用對象的name方法(method)
- 返回值類型爲QVariant,該屬性通常爲常用類型如:數值、字符串、和bool
例如查詢選擇的範圍(pRange)是否存在於表格中:
//下面兩段代碼效果一樣
bInTable = pRange->dynamicCall("Information(12)").toBool()
bInTable = pRange->dynamicCall("Information(int)", 12).toBool()
注:上面代碼塊中12代表的是WdInformation Enum中的wdWithInTable,若選中範圍在表格中則返回true。
4. QVariant property(name)
- 用於獲取對象的名稱爲name屬性(property)
- 返回值類型爲QVariant,該屬性通常爲常用類型如:數值、字符串、和bool
例如獲取範圍(pRange)內的文本:
QString test = pRange->property("Text").toString();