標籤:word處理 qt
Qt擷取office檔案內容
需要擷取word檔案的檔案內容。網上找了好久,大部分都是excel的。而word的很少。所以在這裡記錄一下,方便大家查閱和自己使用。
使用的Qt版本是5.4.2 。
下面通過代碼說明:
-
首先在.pro檔案中加入
QT += axcontainer
-
需要加入以下標頭檔
#include <QAxWidget>
#include <QAxObject>
-
詳細代碼如下
void Qt_word(QString filePath){//指定要開啟檔案的路徑 //QString filePath = "D:/doc/local.doc"; //建立QAxWidget 對象,使其擁有Word的對象 QAxWidget *word=new QAxWidget("Word.Application", 0, Qt::MSWindowsOwnDC); //設定word是否為可見,這裡設定為false。這樣就不會看到word的程式了 word->setProperty("Visible", false); //通過word對象找到它的屬性,Document QAxObject * documents = word->querySubObject("Documents"); //通過Document開啟要擷取檔案內容的檔案 documents->dynamicCall("Open(QString)",filePath);// documents->dynamicCall("Open(QString)",QString::fromLocal8Bit("D:/doc/local.doc")); //擷取當前活動的Document QAxObject *document = word->querySubObject("ActiveDocument"); //從當前活動的Document中擷取paragraphs QAxObject *paragraphs = document->querySubObject("Paragraphs"); //迴圈輸入每一個paragraph for (int ipar = 1; ipar <= paragraphs->property("Count").toInt(); ipar++) { QAxObject *lines = paragraphs->querySubObject("Item(QVariant)", ipar); QAxObject *line = lines->querySubObject("Range"); QString str = line->property("Text").toString(); line->clear(); delete line; lines->clear(); delete lines; str = str.trimmed(); qDebug()<<str; } //關閉Document document->dynamicCall("Close (boolean)", false);// document->dynamicCall("Close (boolean)", false); //退出word word->dynamicCall("Quit()");}
由於對word的內部組織不是很清楚。所以都是一點點摸索出來。
目前只是對word2003進行了測試。2007以上版本還不好使。希望有清楚word內部組織的朋友能夠指點一下。
參考自:http://it-ua.info/news/2015/08/10/parsing-dokumenta-word-na-kartinki-abo-storya-pro-pereddiplomnih-budn.html
2016-04-24 19:21:44
本文出自 “做最好的自己” 部落格,請務必保留此出處http://qiaopeng688.blog.51cto.com/3572484/1767288
Qt擷取office檔案內容