码迷,mamicode.com
首页 > 其他好文 > 详细

Qt获取office文件内容

时间:2016-04-25 01:12:53      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:word处理 qt

       Qt获取office文件内容 

    需要获取word文件的文件内容。网上找了好久,大部分都是excel的。而word的很少。所以在这里记录一下,方便大家查阅和自己使用。

使用的Qt版本是5.4.2

下面通过代码说明:

  1. 首先在.pro文件中加入

    QT       += axcontainer

  2. 需要加入以下头文件

    #include <QAxWidget>

    #include <QAxObject>

  3. 详细代码如下



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文件内容

标签:word处理 qt

原文地址:http://qiaopeng688.blog.51cto.com/3572484/1767288

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!