QT Word 操作

QT提供QAxObject 类操作相对比较晦涩难懂 学习Office操作可借鉴VBA编程,通过VBA编程了解Office相关属性参数等,同时也可以通过微软Office官网进行学习:https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.office.interop.word.paragraphformat?view=word-pia

1、pro 文件增加 

QT += axcontainer。

2、增加 OfficeWordEngine 引擎类。

此处为 抽象基类用于 Excel/Word的提供纯虚函数。

#ifndef OFFICEWORDENGINE_H
#define OFFICEWORDENGINE_H

#include <QString>
#include <QVariant>
#include <QAxObject>
#include <QPair>
class OfficeWordEngine
{
public:
    virtual ~OfficeWordEngine(){}

    virtual bool saveToFile(const QString &savePath)=0;
    virtual bool saveAs(const QString &savePath)=0;
    virtual bool mergeCells(QPair<int,int>beginPoint,QPair<int,int>endPoint)=0;
    virtual bool setCellsValue(QList<QPair<int,int>>cells,QList<QString>values)=0;
    virtual bool open(const QString &sFile,bool bVisible)=0;
    virtual bool replaceText(const QString &sLabel,const QString &sText)=0;
    virtual bool setMarks(const QString &sMark,const QString &sText)=0;
    virtual bool setMultMarks(const QList<QPair<QString,QString>>&sText) =0;
    virtual bool findAndReplace(const QString &oldStr,const QString &newStr,bool replaceAll=true)=0;
    virtual bool setTableContext(QAxObject *table,int row,int cloumn,QVariant sText)=0;
    virtual bool close1()=0;
};
#endif // OFFICEWORDENGINE_H

3、实例化  WordEngine类,该类继承于 OfficeWordEngine基类。并实现具体的纯虚函数。

私有成员变量中WordEnginePrivate *d_ptr  为具体的内部实例化类,此处主要用到二进制兼容以及源码兼容,在 QT源码中体现 dq指针。

#ifndef WORDENGINE_H
#define WORDENGINE_H

#include "officewordengine.h"
class WordEnginePrivate;
class WordEngine : public OfficeWordEngine
{
public:
    WordEngine();
    ~WordEngine();
    bool saveToFile(const QString &savePath);
    bool saveAs(const QString &savePath);

    bool mergeCells(QPair<int,int>beginPoint,QPair<int,int>endPoint);
    bool setCellsValue(QList<QPair<int,int>>cells,QList<QString>values);
    bool open(const QString &sFile,bool bVisible=false);
    bool replaceText(const QString &sLabel,const QString &sText);
    bool setMarks(const QString &sMark,const QString &sText);
    bool setMultMarks(const QList<QPair<QString,QString>>&sText);
    bool findAndReplace(const QString &oldStr,const QString &newStr,bool replaceAll=true);
    bool setTableContext(QAxObject *table,int row,int cloumn,QVariant sText);
    bool close1();
    QAxObject *getRange(int row,int cloumn);
    QAxObject *getRange(QPair<int,int> point);

    bool setLeftHorizontalAlignment(QAxObject *pRange);
    bool setRigthHorizontalAlignment(QAxObject *pRange);
    bool setCenterAlignment(QAxObject *pRange);

    //插入一个几行几列表格
    QAxObject *insertTable(QString sLabel,int row,int column);
    //插入一个几行几列表格 并设置表头
    QAxObject *insertTable(QString sLabel,int row,int column,QStringList headList);
    //设置列宽
    void setColumnWidth(QAxObject *table,int column, int width);
    //设置行高
    void setRowHeight(int row, float height);
    void SetTableCellString(QAxObject *table, int row,int column,QString text);

    bool setTableContext(QAxObject *table,int row,int cloumn,const QVariant &value);

    bool addTableRow(QAxObject *table, int nRow, int rowCount);

    bool addTableRow( int nRow, int rowCount);
    //Selection.Rows.Delete
    bool deleteRow(int nRow);
    int getRowCount();
    int getCloumnCount();

private:
    WordEnginePrivate *d_ptr = NULL;
};

#endif // WORDENGINE_H

4、WordEngine.cpp 文件

#include "wordengine.h"
#include "wordengineprivate.h"

WordEngine::WordEngine()
{
    d_ptr = new WordEnginePrivate;
}

 WordEngine::~WordEngine()
 {
     if (d_ptr)delete d_ptr;
 }

bool WordEngine::saveToFile(const QString &savePath)
{
    return d_ptr->saveToFile(savePath);
}

 bool WordEngine::saveAs(const QString &savePath)
 {
    return d_ptr->saveAs(savePath);
 }

 bool WordEngine::mergeCells(QPair<int,int>beginPoint,QPair<int,int>endPoint)
 {
     return d_ptr->mergeCells(beginPoint,endPoint);
 }
 bool WordEngine::setCellsValue(QList<QPair<int,int>>cells,QList<QString>values)
 {
    return d_ptr->setCellsValue(cells,values);
 }


bool WordEngine::open(const QString &sFile,bool bVisible)
{
    return d_ptr->open(sFile,bVisible);
}
bool WordEngine::replaceText(const QString &sLabel,const QString &sText)
{
    return d_ptr->replaceText(sLabel,sText);
}
bool WordEngine::setMarks(const QString &sMark,const QString &sText)
{
    return d_ptr->setMarks(sMark,sText);
}



bool WordEngine::setMultMarks(const QList< QPair<QString,QString> >& sText)
{
    return d_ptr->setMultMarks(sText);
}

bool WordEngine::findAndReplace(const QString &oldStr,
                 const QString &newStr,bool replaceAll)
{
    return d_ptr->findAndReplace(oldStr,newStr,replaceAll);
}
bool WordEngine::setTableContext(QAxObject *table,int row,
                       int cloumn,QVariant sText)
{
    return d_ptr->setTableContext(table,row,cloumn,sText);
}
bool WordEngine::close1()
{
    return d_ptr->close1();
}

QAxObject *WordEngine::getRange(int row,int cloumn)
{
    return d_ptr->getRange(row,cloumn);
}
QAxObject *WordEngine::getRange(QPair<int,int> point)
{
  return getRange(point.first,point.second);
}

bool WordEngine::setLeftHorizontalAlignment(QAxObject *p)
{
    return d_ptr->setLeftHorizontalAlignment(p);
}
bool WordEngine::setRigthHorizontalAlignment(QAxObject *p)
{
    return d_ptr->setRigthHorizontalAlignment(p);
}
   bool WordEngine::setCenterAlignment(QAxObject *pRange)
   {
        return d_ptr->setCenterAlignment(pRange);
   }


//插入一个几行几列表格
QAxObject * WordEngine::WordEngine::insertTable(QString sLabel,int row,int column)
{
    return d_ptr->insertTable(sLabel,row,column);
}
//插入一个几行几列表格 并设置表头
QAxObject * WordEngine::WordEngine::insertTable(QString sLabel,int row,int column,QStringList headList)
{
    return d_ptr->insertTable(sLabel,row,column,headList);
}
//设置列宽
void WordEngine::setColumnWidth(QAxObject *table,int column, int width)
{
    d_ptr->setColumnWidth(table,column,width);
}

void WordEngine::setRowHeight( int row, float height)
{
     d_ptr->setRowHeight(row,height);
}
void WordEngine::SetTableCellString(QAxObject *table, int row,int column,QString text)
{
    d_ptr->SetTableCellString(table,row,column,text);
}

bool WordEngine::setTableContext(QAxObject *table,int row,int cloumn,const QVariant &value)
{
    return d_ptr->setTableContext(table,row,cloumn,value);
}

bool WordEngine::addTableRow(QAxObject *table, int nRow, int rowCount)
{
    return d_ptr->addTableRow(table,nRow,rowCount);
}

bool WordEngine::addTableRow( int nRow, int rowCount)
{
    return d_ptr->addTableRow(nRow,rowCount);
}

//Selection.Rows.Delete
bool WordEngine::deleteRow(int nRow)
{
    return d_ptr->deleteRow(nRow);
}
int WordEngine::getRowCount()
{
    return d_ptr->getRowCount();
}
int WordEngine::getCloumnCount()
{
    return d_ptr->getCloumnCount();
}

5、WordEnginePrivate 头文件

#ifndef WORDENGINEPRIVATE_H
#define WORDENGINEPRIVATE_H

#include "officewordengine.h"
#include <QObject>
#include <QAxObject>
#include <QAxWidget>
#include <QtCore>

class WordEnginePrivate : public OfficeWordEngine
{
public:
    WordEnginePrivate();
    virtual ~WordEnginePrivate();

    bool saveToFile(const QString &savePath);
    bool saveAs(const QString &savePath);
    bool mergeCells(QPair<int,int>beginPoint,QPair<int,int>endPoint);
    bool setCellsValue(QList<QPair<int,int>>cells,QList<QString>values);
    bool open(const QString &sFile,bool bVisible);
    bool replaceText(const QString &sLabel,const QString &sText);
    bool setMarks(const QString &sMark,const QString &sText);
    bool setMultMarks(const QList<QPair<QString,QString>>&sText);
    bool findAndReplace(const QString &oldStr,const QString &newStr,bool replaceAll=true);
    bool setTableContext(QAxObject *table,int row,int cloumn,QVariant sText);
    bool close1();

    QAxObject *getRange(int row,int cloumn);
    //QAxObject *getRange(QPair<int,int> point);

    bool setLeftHorizontalAlignment(QAxObject *pRange);
    bool setRigthHorizontalAlignment(QAxObject *pRange);
    bool setCenterAlignment(QAxObject *pRange);
    
    //插入一个几行几列表格
    QAxObject *insertTable(QString sLabel,int row,int column);
    //插入一个几行几列表格 并设置表头
    QAxObject *insertTable(QString sLabel,int row,int column,QStringList headList);
    //设置列宽
    void setColumnWidth(QAxObject *table,int column, int width);

    void setRowHeight( int row, float height);

    void SetTableCellString(QAxObject *table, int row,int column,QString text);

   // bool setTableContext(QAxObject *table,int row,int cloumn,const QVariant &value);

    bool addTableRow(QAxObject *table, int nRow, int rowCount);

    bool addTableRow( int nRow, int rowCount);

    bool setTableContext(QAxObject *table,std::pair<int,int>rowCloumn,const QVariant &value);

    bool setTableContext(const QString& wordFileName,std::pair<int,int>rowCloumn,const QVariant &value);

    bool deleteRow(int nRow);
    int getRowCount();
    int getCloumnCount();

private:
    inline bool isNull(QAxObject *);
    inline bool existTable();
private:

    QAxObject *m_pWord = NULL;      //指向整个Word应用程序
    QAxObject *m_pWorkDocuments = NULL;  //指向文档集,Word有很多文档
    QAxObject *m_pWorkDocument = NULL;   //指向m_sFile对应的文档,就是要操作的文档

    QString m_sFile;
    bool m_bIsOpen =false;
    bool m_bNewFile =false;
};

#endif // WORDENGINEPRIVATE_H

6、WordEnginePrivate.cpp 文件

#include "wordengineprivate.h"
#include "qt_windows.h"
#include <QString>
#include <iostream>
#include <QAxObject>
#include <QAxWidget>
#include <QtCore>
#include <QPair>
WordEnginePrivate::WordEnginePrivate()
{
    HRESULT result = OleInitialize(0);

    if (result != S_OK && result != S_FALSE){
        qDebug()<<QString("Could not initialize OLE (error %x)").arg((unsigned int)result);
    }
}
WordEnginePrivate::~WordEnginePrivate()
{
    OleUninitialize();
}

bool WordEnginePrivate::saveToFile(const QString &sSavePath)
{
    if(m_bIsOpen && m_pWorkDocument)
    {
        qDebug()<<m_bNewFile;
        if(m_bNewFile){
            m_pWorkDocument->dynamicCall("Save()");
        }
        else{
            //m_pWorkDocument->dynamicCall("SaveAs (const QString&,int,const QString&,const QString&,bool,bool)",
            //                           m_sFile,56,QString(""),QString(""),false,false);
            //qDebug()<<sSavePath;
            m_pWorkDocument->dynamicCall("SaveAs (const QString&)", sSavePath);
            //m_pWorkDocument->dynamicCall("SaveAs (const QString&)","");
        }
    }
    qDebug()<<"save Done.";
    return true;
}
/***
 * 保存文件另存为操作
*/
bool WordEnginePrivate::saveAs(const QString &savePath)
{
    return m_pWorkDocument->dynamicCall("SaveAs (const QString&)",
                                        savePath).toBool();
}

bool  WordEnginePrivate::mergeCells(QPair<int,int>beginPoint,QPair<int,int>endPoint)
{
    if (!existTable())
        return false;

    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",1);
    QAxObject* cell11 = onTable->querySubObject("Cell(int,int)",beginPoint.first,beginPoint.second);
    QAxObject* cell19 = onTable->querySubObject("Cell(int,int)",endPoint.first,endPoint.second);

    cell11->querySubObject("Range")->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphLeft");
    cell19->querySubObject("Range")->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphLeft");
    bool isOk = cell11->dynamicCall("Merge(QAxObject*)", cell19->asVariant()).toBool();

    return isOk;
}


bool WordEnginePrivate::setCellsValue(QList<QPair<int,int>>cells,QList<QString>values)
{
#if 0
    if(!isNull(m_pWorkDocument))
        return false;

    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    if(!isNull(pTable))
        return false;

    QAxObject* onTable = pTable->querySubObject("Item(int)",/*tableIndex*/1);
    if(!onTable->isNull())
        return false;
#else
    if (!existTable())
        return false;
    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",1);
#endif
    int index =0;
    QList<QPair<int,int>>::const_iterator it;

    for (it = cells.begin(); it != cells.end(); it ++) {
        QPair<int,int> oneMarkPair = *it;
        int  row = oneMarkPair.first;
        int  column = oneMarkPair.second;

        QAxObject *range = onTable->querySubObject("Cell(int,int)", row, column);
        //qDebug() << Q_FUNC_INFO << __LINE__ << range->setProperty("HorizontalAlignment", -4131);

        range->dynamicCall("Select(void)");

        range->querySubObject("Range")->setProperty("Text", values.at(index));
        //range->dynamicCall("SetValue(const QString&)", values.at(index));
        index ++;

    }
    return true;
}


bool WordEnginePrivate::open(const QString &sFile,bool bVisible)
{
    //新建一个word应用程序
    m_pWord = new QAxObject();
    bool bFlag = m_pWord->setControl( "word.application" );
    //     m_pWord=new QAxWidget("Word.Application", 0, Qt::MSWindowsOwnDC);
    //     bool bFlag = m_pWord->setControl( "Word.Application" );
    qDebug()<<"sFile"<<sFile;
    if(!bFlag)
    {
        qDebug()<<"!bFlag";
        return false;
    }
    m_pWord->setProperty("Visible", bVisible);
    //获取所有的工作文档
    m_pWorkDocuments = m_pWord->querySubObject("Documents");
    if(!m_pWorkDocuments)
    {
        qDebug()<<"!m_pWorkDocuments";
        return false;
    }
    //以文件template.dot为模版新建一个文档
    // m_pWorkDocuments->dynamicCall("Add(QString)",sFile);

    m_pWorkDocuments->querySubObject("Open(const QString&)",sFile);
    this->m_sFile = sFile;


    //获取当前激活的文档
    m_pWorkDocument = m_pWord->querySubObject("ActiveDocument");
    if(m_pWorkDocument)
        m_bIsOpen = true;
    else
        m_bIsOpen = false;

    qDebug()<<"m_bIsOpen"<<m_bIsOpen;
    return m_bIsOpen;
}
bool WordEnginePrivate::replaceText(const QString &sLabel,const QString &sText)
{
    if(!m_pWorkDocument){
        return false;
    }
    //获取文档中名字为sLabel的标签
    QAxObject *pBookmark = m_pWorkDocument->querySubObject("Bookmarks(QString)",sLabel);
    if(!pBookmark->isNull ())
    {
        pBookmark->dynamicCall("Select(void)");
        pBookmark->querySubObject("Range")->setProperty("Text",sText);
        delete pBookmark;
    }
    return true;
}
bool WordEnginePrivate::setMarks(const QString &strMark,const QString &sText)
{
    if (!isNull(m_pWorkDocument))
        return false;

    QAxObject* bookmarkCode = NULL;
    bookmarkCode = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", strMark);

    //选中标签,将字符textg插入到标签位置
    if(bookmarkCode) {
        bookmarkCode->dynamicCall("Select(void)");
        bookmarkCode->querySubObject("Range")->setProperty("Text", sText);
        return true;
    }
    return false;
}

bool WordEnginePrivate::setMultMarks(const QList<QPair<QString,QString>>&sText)
{

    if (!isNull(m_pWorkDocument))
        return false;

    QAxObject* bookmarkCode = NULL;

    QList<QPair<QString,QString>>::const_iterator it;

    for (it = sText.begin(); it != sText.end(); it++) {

        QPair<QString,QString> oneMarkPair = *it;
        QString  strMark = oneMarkPair.first;
        QString  strText = oneMarkPair.second;

        bookmarkCode = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", strMark);
        //选中标签,将字符textg插入到标签位置
        if(bookmarkCode) {
            bookmarkCode->dynamicCall("Select(void)");
            bookmarkCode->querySubObject("Range")->setProperty("Text", strText);
        }else
            return false;
    }
    return true;
}

bool WordEnginePrivate::findAndReplace(const QString &oldStr,
                                       const QString &newStr,bool replaceAll)
{
    if(!isNull(m_pWorkDocument))
        return false;
    auto content = m_pWorkDocument->querySubObject("Content()");
    if (!isNull(content))
        return false;

    auto find = content->querySubObject("Find");
    if (!isNull(find))
        return false;

    qDebug() <<Q_FUNC_INFO << "content: "<< content <<endl;
    qDebug() <<Q_FUNC_INFO << "find: "<< find <<endl;

    bool bMatchCase      = false;
    bool bMatchWholeWord = false;
    bool bMatchWildCards = false;
    bool bReplaceAll     = replaceAll;

    QVariantList vl = { oldStr, bMatchCase, bMatchWholeWord,
                        bMatchWildCards, false, false, true,
                        1, false, newStr,  bReplaceAll ? "2" : "1" };

    return find->dynamicCall("Execute(QString,bool,bool,bool,bool,bool,bool,int,bool,QString,int)",vl).toBool();

}
//bool WordEnginePrivate::setTableContext(QAxObject *table,int row,
//                                 int cloumn,QVariant sText)
//{
//    if (table->isNull() || row <=0 || cloumn <=0)
//        return false;

//    QAxObject *cell = table->querySubObject("Cell(int, int)",row,cloumn);
//    QAxObject *cellRange = cell->querySubObject("Range");

//    return  cellRange->dynamicCall("Text", value).toBool();
//}
bool WordEnginePrivate::close1()
{

    if(m_pWorkDocument)
        m_pWorkDocument->dynamicCall("Close(boolean)", true);

    if(m_pWord)
        m_pWord->dynamicCall("Quit(void)");

    if(m_pWorkDocuments)
        delete m_pWorkDocuments;

    if(m_pWord)
        delete m_pWord;

    m_pWorkDocument = NULL;
    m_pWorkDocuments = NULL;
    m_pWord = NULL;

    m_bIsOpen   = false;
    m_bNewFile  = false;
    return true;
}
QAxObject *WordEnginePrivate::getRange(int row,int cloumn)
{
    if (!existTable())
        return false;
    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",1);

    QAxObject *cell = onTable->querySubObject("Cell(int, int)",row,cloumn);
    return cell->querySubObject("Range");

}

bool WordEnginePrivate::setLeftHorizontalAlignment(QAxObject *pRange)
{
    if ( pRange == nullptr|| !existTable())
        return false;
      pRange->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphLeft");
        return true;

}
bool WordEnginePrivate::setRigthHorizontalAlignment(QAxObject *pRange)
{
    if ( pRange == nullptr||!existTable())
        return false;
    pRange->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphRight");
    return true;
}
bool WordEnginePrivate::setCenterAlignment(QAxObject *pRange)
{
    if ( pRange == nullptr||!existTable())
        return false;
    pRange->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter");
    return true;
}


//插入一个几行几列表格
QAxObject *WordEnginePrivate::insertTable(QString sLabel,int row,int column)
{
    QAxObject *bookmark = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", sLabel);
    if(!bookmark->isNull ())
    {
        bookmark->dynamicCall("Select(void)");
        QAxObject *selection = m_pWord->querySubObject("Selection");

        selection->dynamicCall("InsertAfter(QString&)", "\n");
        //selection->dynamicCall("MoveLeft(int)", 1);
        //selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter");
        selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphLeft");
        selection->dynamicCall("TypeText(QString&)", "Table Test");//设置标题

        QAxObject *range = selection->querySubObject("Range");
        QAxObject *tables = m_pWorkDocument->querySubObject("Tables");
        QAxObject *table = tables->querySubObject("Add(QVariant,int,int)",range->asVariant(),row,column);

        for(int i=1;i<=6;i++)
        {
            QString str = QString("Borders(-%1)").arg(i);
            QAxObject *borders = table->querySubObject(str.toLatin1().constData());
            borders->dynamicCall("SetLineStyle(int)",1);
        }
        return table;
    }
    return nullptr;
}

//插入一个几行几列表格 并设置表头
QAxObject *WordEnginePrivate::insertTable(QString sLabel,int row,int column,QStringList headList)
{

    QAxObject *bookmark = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", sLabel);
    if(headList.size() != column){
        return NULL;
    }
    if(bookmark)
    {
        bookmark->dynamicCall("Select(void)");
        QAxObject *selection = m_pWord->querySubObject("Selection");

        selection->dynamicCall("InsertAfter(QString&)", "\r\n");
        //selection->dynamicCall("MoveLeft(int)", 1);
        selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphCenter");
        //设置标题
        //selection->dynamicCall("TypeText(QString&)", "Table Test");

        QAxObject *range = selection->querySubObject("Range");
        QAxObject *tables = m_pWorkDocument->querySubObject("Tables");
        QAxObject *table = tables->querySubObject("Add(QVariant,int,int)",range->asVariant(),row,column);
        //表格自动拉伸列 0固定  1根据内容调整  2 根据窗口调整
        table->dynamicCall("AutoFitBehavior(WdAutoFitBehavior)", 2);

        //设置表头
        for(int i=0;i<headList.size();i++){
            table->querySubObject("Cell(int,int)",1,i+1)->querySubObject("Range")->dynamicCall("SetText(QString)", headList.at(i));
            //加粗
            table->querySubObject("Cell(int,int)",1,i+1)->querySubObject("Range")->dynamicCall("SetBold(int)", true);
        }

        for(int i=1;i<=6;i++)
        {
            QString str = QString("Borders(-%1)").arg(i);
            QAxObject *borders = table->querySubObject(str.toLatin1 ().constData());
            borders->dynamicCall("SetLineStyle(int)",1);
        }
        return table;
    }
    return nullptr;
}

//设置列宽
void WordEnginePrivate::setColumnWidth(QAxObject *table,int column, int width)
{
    if(!table) return;
    table->querySubObject("Columns(int)",column)->setProperty("Width",width);

}

void WordEnginePrivate::setRowHeight( int row, float height)
{

    qDebug()<<Q_FUNC_INFO<<"begin   row  "<<row<<"height"<<height;
    if(!m_pWorkDocument)
        return;
    QAxObject * pTables = m_pWorkDocument->querySubObject("Tables");
    if(!pTables) return;
    QAxObject* pTable = pTables->querySubObject("Item(int)",1);
    if(!pTable)return;
    QAxObject* pRows = pTable->querySubObject("Rows");
    if(!pRows)
        return;
    QAxObject* pRow = pRows->querySubObject("Item(int)",row);
    if(!pRow)
        return;
    pRow->setProperty("Height",int(height));
    qDebug()<<Q_FUNC_INFO<<"end   row  "<<row<<"height"<<height;
}

void WordEnginePrivate::SetTableCellString(QAxObject *table, int row,int column,QString text)
{
    if(!table) return;
    QAxObject *cell = table->querySubObject("Cell(int,int)",row,column);
    if(!cell) return;

    cell->dynamicCall("Select(void)");
    cell->querySubObject("Range")->setProperty("Text", text);
}

bool WordEnginePrivate::setTableContext(QAxObject *table,int row,int cloumn,const QVariant value)
{
    if (table->isNull() || row <=0 || cloumn <=0)
        return false;

    QAxObject *cell = table->querySubObject("Cell(int, int)",row,cloumn);
    QAxObject *cellRange = cell->querySubObject("Range");

    return  cellRange->dynamicCall("Text", value).toBool();
}

bool WordEnginePrivate::addTableRow(QAxObject *table, int nRow, int rowCount)
{
    if (table->isNull() || nRow <=0 || rowCount <= 0)
        return false;

    QAxObject* rows = table->querySubObject("Rows");

    int Count = rows->dynamicCall("Count").toInt();
    qDebug() << Q_FUNC_INFO << Count <<endl;

    if(0 <= nRow && nRow <=Count)
    {
        for(int i = 0; i < rowCount; ++i)
        {
            QString sPos = QString("Item(%1)").arg(nRow + i);
            QAxObject* row = rows->querySubObject(sPos.toStdString().c_str());
            QVariant param = row->asVariant();
            QVariant rdata = rows->dynamicCall("Add(Variant)", param);
            if (!rdata.toBool())
                return false;
        }
    }
    return true;
}
/**
 * @brief WordEnginePrivate::addTableRow
 * @param wordFileName
 * @param nRow 起始行
 * @param rowCount : 插入函数
 * @return
 */
bool WordEnginePrivate::addTableRow( int nRow, int rowCount)
{

    QAxObject* document = m_pWorkDocument;
    QAxObject* pTable = document->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",/*tableIndex*/1);

#if 0 // 方式一
    qDebug() << Q_FUNC_INFO << __LINE__ <<endl;
    if (onTable->isNull() || nRow <=0 || rowCount <=0)
        return false;

    QAxObject* rows = onTable->querySubObject("Rows");

    int Count = rows->dynamicCall("Count").toInt();
    qDebug() << Q_FUNC_INFO <<__LINE__<< Count <<endl;
    qDebug() << Q_FUNC_INFO <<__LINE__<<"nRow: "<< nRow <<endl;
    if(0 <= nRow && nRow <=Count)
    {
        for(int i = 0; i < rowCount; ++i)
        {
            QString sPos = QString("Item(%1)").arg(nRow + i);
            QAxObject* row = rows->querySubObject(sPos.toStdString().c_str());
            QVariant param = row->asVariant();
            rows->dynamicCall("Add(Variant)", param);
        }
    }
    return true;
#else // 方式二
    QAxObject *cell =onTable->querySubObject("Cell(int, int)",nRow,1);
    cell->dynamicCall("Select(void)");

    QAxObject *selection = m_pWord->querySubObject("Selection");
    //selection->querySubObject("ParagraphFormat")->dynamicCall("Alignment", "wdAlignParagraphLeft");
    //Selection.InsertRowsBelow 1
    qDebug() << Q_FUNC_INFO << "rowCount: "<< rowCount;
    for (int i=0;i<rowCount;i++){
        selection->dynamicCall("InsertRowsBelow(Variant)",1);

    }
    return  true;

#endif
}


bool WordEnginePrivate::setTableContext(QAxObject *table,std::pair<int,int>rowCloumn,const QVariant &value)
{
    int row = rowCloumn.first;
    int cloumn =  rowCloumn.second;

    if (table->isNull() || row <=0 || cloumn <=0)
        return false;

    QAxObject *cell = table->querySubObject("Cell(int, int)",row,cloumn);
    QAxObject *cellRange = cell->querySubObject("Range");

    return  cellRange->dynamicCall("Text", value).toBool();
}

bool WordEnginePrivate::setTableContext(const QString& wordFileName,
                                        std::pair<int,int>rowCloumn,const QVariant &value)
{
    Q_UNUSED(wordFileName);
#if 0
    int row = rowCloumn.first;
    int cloumn =  rowCloumn.second;

    // 对象以及初始化
    if (wPrivate->bIsOpen()){
        qDebug() << Q_FUNC_INFO << ": " << wPrivate->pWorkDocument() ;
        QAxObject* pTable = wPrivate->pWorkDocument()->querySubObject( "Tables");
        qDebug() << Q_FUNC_INFO <<pTable <<endl;
        if(pTable->isNull())
            return false;
        QAxObject* onTable = pTable->querySubObject("Item(int)",/*tableIndex*/1);
        qDebug() << Q_FUNC_INFO << onTable <<endl;
        return wPrivate->setTableContext(onTable,row,cloumn,value);
    }

    //隐式的打开一个word应用程序
#if defined(Q_OS_WIN)
    HRESULT r = OleInitialize(0);
    if (r != S_OK && r != S_FALSE) {
        qWarning("Qt: Could not initialize OLE (error %x)", (unsigned int)r);
    }
#endif

    QAxWidget word("Word.Application");
    word.setProperty("Visible", false);

    //获取所有工作文档
    QAxObject * documents = word.querySubObject("Documents");
    //创建一个word文档
    documents->querySubObject("Open(QString)",wordFileName);;
    //获取当前激活的文档
    QAxObject * document = word.querySubObject("ActiveDocument");

    QAxObject* pTable = document->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",1);

    if (onTable->isNull() || row <=0 || cloumn <=0)
        return false;

    QAxObject *cell = onTable->querySubObject("Cell(int, int)",row,cloumn);
    QAxObject *cellRange = cell->querySubObject("Range");

    cellRange->dynamicCall("Text", value).toBool();

    //关闭退出
    document->dynamicCall("Close (boolean)", true);
    word.dynamicCall("Quit (void)");

    OleUninitialize();
    return true;
#else
    if (!existTable())
        return false;

    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",1);
    return setTableContext(onTable,rowCloumn,value);
#endif
}

bool WordEnginePrivate::deleteRow(int nRow)
{
    //Selection.Rows.Delete

#if 0
    QAxObject* document = m_pWorkDocument;
    QAxObject* pTable = document->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",/*tableIndex*/1);


    QAxObject *cell =onTable->querySubObject("Cell(int, int)",nRow,1);
    cell->dynamicCall("Select(void)");

    QAxObject *selection = m_pWord->querySubObject("Selection");
    //Selection.InsertRowsBelow 1

    QAxObject *rows=selection->querySubObject("Rows(void)");
    return rows->dynamicCall("Delete(void)").toBool();
    //return  true;
#else
    // 添加修改的时候 表格全部内容判断 单元格为空时,删除选中行
    QAxObject* document = m_pWorkDocument;
    QAxObject* pTable = document->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",/*tableIndex*/1);

    int size = this->getRowCount();

    for (int i=0;i<size;i++) {
        QAxObject *cell =onTable->querySubObject("Cell(int, int)",nRow,1);
        QString text = cell->querySubObject("Range")->property("Text").toString();

        if (text.isEmpty() || text == "\r\u0007") {
            cell->dynamicCall("Select(void)");

            QAxObject *selection = m_pWord->querySubObject("Selection");
            //Selection.InsertRowsBelow 1

            QAxObject *rows=selection->querySubObject("Rows(void)");
            rows->dynamicCall("Delete(void)").toBool();
        }
    }


#endif
    return true;
}

int WordEnginePrivate::getRowCount()
{
    if (!existTable())
        return false;

    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",1);
    QAxObject* Columns = onTable->querySubObject("Rows");
    return  Columns->dynamicCall("Count").toInt();
}
int WordEnginePrivate::getCloumnCount()
{
    if (!existTable())
        return false;

    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    QAxObject* onTable = pTable->querySubObject("Item(int)",1);

    QAxObject* rows = onTable->querySubObject("Columns");

    return  rows->dynamicCall("Count").toInt();
}

bool WordEnginePrivate::isNull(QAxObject *p)
{
    return !(p->isNull());
}

bool WordEnginePrivate::existTable()
{
    if(!isNull(m_pWorkDocument))
        return false;

    QAxObject* pTable = m_pWorkDocument->querySubObject( "Tables" );
    if(!isNull(pTable))
        return false;

    QAxObject* onTable = pTable->querySubObject("Item(int)",/*tableIndex*/1);
    if(onTable->isNull())
        return false;

    return true;
}

 

7、源码下载链接:https://download.csdn.net/download/m1223853767/13985742

  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值