從一個word文件中讀取所有的表格和標題(2)


上一篇文章主要講了從word底層xml中獲取表格和標題的方法,但是存在一個問題:word文件必須是docx格式的。如果為doc格式的,可以有兩種解決方案:

一、把doc文件轉換成docx格式文件,用上一種辦法來處理

二、利用com組件和word的標簽機制去處理

下面直接貼代碼:

1)獲取表格數據

 1 void MyWord::getTableData( const int index, QVector<QVector<QString> > &vec )
 2 {
 3         m_word = new QAxObject(parent);
 4         if(!m_word->setControl("Word.Application"))
 5     {
 6         QMessageBox::warning(0, tr("警告"), tr("綁定word控件失敗"), tr("確定"));
 7         return ;
 8     }
 9     m_word->setProperty("Visible", false); //設置窗體不可見
10     m_word->setProperty("DisplayAlerts", false); //不現實警告信息
11 
12     m_documents = m_word->querySubObject("Documents");
13     m_documents->dynamicCall("Open(const QString &)", filename); //打開文件
14     m_document = m_word->querySubObject("ActiveDocument"); //獲取當前被激活文檔
15 
16     QAxObject *table = m_document->querySubObject("Tables(int)", index); //獲取表格
17     if(!table)
18     {
19         return ;
20     }
21 23     int rowCnt = table->querySubObject("Rows")->property("Count").toInt(); //行數
24     int colCnt = table->querySubObject("Columns")->property("Count").toInt(); //列數
25     for(int nR = 1; nR <= rowCnt; ++nR)
26     {
27         QVector<QString> tmpVec;
28         for(int nC = 1; nC <= colCnt; ++nC)
29         {
30             QAxObject *cell = table->querySubObject("Cell(int, int)", nR, nC);//每一個單元格
31             if(!cell)
32             {
33                 tmpVec.push_back("");
34                 continue;
35             }
36             QString text = cell->querySubObject("Range")->property("Text").toString();//獲取單元格文本
37             tmpVec.push_back(text.remove(text.size() - 1, 1));//去除文本的換行符
38         }
39         vec.push_back(tmpVec);
40     }
41 }    

 2)讀取標簽相關區域文本

QString MyWord::getTextFromBookmark( const int index /*= 1*/ )
{
    if(index < 1 || index > getBookmarkCount() && !m_document)
    {
        return "";
    }

    QAxObject *bookmark = m_document->querySubObject("Bookmarks(int)", index);
    if(bookmark)
    {
        QAxObject *range = bookmark->querySubObject("Range");
        if(range)
        {
            return range->property("Text").toString();
        }
    }
    return "";
}

QString MyWord::getTextFromBookmark( const QString &bookmarkName )
{
    if(!m_document)
    {
        return "";
    }

    QAxObject *bookmark = m_document->querySubObject("Bookmarks(const QString &)", bookmarkName);
    if(bookmark)
    {
        QAxObject *range = bookmark->querySubObject("Range");
        if(range)
        {
            return range->property("Text").toString();
        }
    }
    return "";
}

3)如何插入標簽

選中要插如標簽的文本,word插入->標簽,按照提示操作即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM