Qt 使用QAxObject操作Word

本文介绍如何使用Qt通过COM接口操作Word文档,包括创建文档、设置排版、插入文字和图片、创建及填充表格等功能。文章提供了详细的代码示例,帮助开发者快速掌握Qt与Word文档交互的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为最近项中需要生成报表,所以网上查了资料,因为VB看不懂所以总结的也不多,在实现中没有使用标签只是以光标的位置来插入,包括:创建文件,排版方式,添加文字,添加图片,添加表格,表格添加文字(图片),光标移动到尾部,光标跳转(类似tab)等

添加 QT += axcontainer

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

/*
    创建word
*/

void MainWindow::open()
{
    m_pWord = new QAxObject();
    bool flag = m_pWord->setControl( "Word.Application" );
    if(!flag)
    {
        return;
    }
    m_pWord->setProperty("Visible", true);

    QAxObject *document = m_pWord->querySubObject("Documents");
    if(!document)
    {
        return ;
    }

    //获取当前激活的文档
    m_pWorkDocument = m_pWord->querySubObject("ActiveDocument");
}

/*
 * 排版方式
 * 纵行、横行
*/

void MainWindow::setype(bool type)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    if(type)
    {
        selection->querySubObject("PageSetup")->setProperty("Orientation","wdOrientLandscape");
    }else{
        selection->querySubObject("PageSetup")->setProperty("Orientation","wdOrientPortrait");
    }
}

/*
 * 获取页宽
*/

int MainWindow::pageWidth()
{
    int width;
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    width = selection->querySubObject("PageSetup")->property("PageWidth").toInt();;
    return width;
}

/*
*设置字号
*/

void MainWindow::setFontSize(int size)
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    selection->querySubObject("Font")->setProperty("Size",size);
}

/*
   设置对齐方式
*/

void MainWindow::setAlignment(int index)
{
    QAxObject *selection = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    if(index == 0)
    {
      selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphCenter");
    }
    if(index == 1)
    {
       selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphJustify");
    }
    if(index == 2)
    {
       selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphRight");
    }
    if(index == 3)
    {
       selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphLeft");
    }
}


/*
   插入文字
*/

void MainWindow::typeText(QString text)
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    selection->dynamicCall("TypeText(const QString&)",text);
}
/*
    插入图片
*/

void MainWindow::AddPicture(QString file)
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    QString filename = file;
    filename.replace("/","\\");
    QAxObject *Inlineshapes = selection->querySubObject("InlineShapes");
    Inlineshapes->dynamicCall("AddPicture(const QString&)",filename);
    delete Inlineshapes;
}

/*
    插入回车
*/

void MainWindow::insertEnter()
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    selection->dynamicCall("TypeParagraph(void)");
}

/*
 * 光标移到末尾,跳出单元格
*/
void MainWindow::moveForEnd()
{
    QAxObject* selection = m_pWord->querySubObject("Selection");
    QVariantList params;
    params.append(6);
    params.append(0);
    selection->dynamicCall("EndOf(QVariant&, QVariant&)", params).toInt();
}

/*
   创建表格
   QStringList headList 添加表头
*/

QAxObject* MainWindow::createTable(int row, int column,QStringList headList)
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return false;
    }
    selection->dynamicCall("InsertAfter(QString&)", "\r\n");

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

    table->setProperty("Style","网格型");
    //表格自动拉伸列 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);
    }
    return table;
}

/*
   填充表格
*/

void MainWindow::setCellText(QAxObject *table, int row, int column, QString text)
{
    QAxObject* range = table->querySubObject("Cell(int, int)",row+1,column+1)->querySubObject("Range");
    if( range)
    {
        return;
    }

    range->dynamicCall("SetText(QString)", text);
}

/*
  表格插入图片
*/
void MainWindow::setAddPicture(QAxObject *table, int row, int column, QString picPath)
{
    QAxObject* range = table->querySubObject("Cell(int, int)",row+1,column+1)->querySubObject("Range");
    if(!range)
    {
        return;
    }
    range->querySubObject("InlineShapes")->dynamicCall("AddPicture(const QString&)",picPath);
}

/*
   光标跳转,类似表格中的tab
*/

void MainWindow::moveRight()
{
    QAxObject* selection  = m_pWord->querySubObject("Selection");
    if(!selection)
    {
        return;
    }
    selection->dynamicCall("MoveRight(int)",1);
}

/*特殊样例*/

void MainWindow::Example()
{
    QStringList header;

    newTable(1,2,header);//创建表格

    typeText(tr("文字1"));//添加文字
    insertEnter();//换行
    insertText("");
    AddPicture("图像1");//插入图片

    moveRight();//将光标插入到下个单元格中

    typeText(tr("文字2"));
    insertEnter();
    insertText("");
    AddPicture("图像2");

    moveForEnd();//光标跳出表格

    /*然后,可以做其他操作了*/

}

QT中的`QAxObject`是一个用于创建并管理COM(Component Object Model)部件的对象,它允许你在Qt应用程序中集成和支持像Microsoft Word这样的Windows桌面应用。要在QT中通过`QAxObject`来操作Word并设置页码,你需要遵循以下几个步骤: 1. 首先,确保已经包含了相应的库支持,如`qaxcontainer`,它包含了对`QAxObject`的支持。 2. 创建一个`QAxObject`实例,指向Word应用程序: ```cpp QAxObject* wordApp = new QAxObject("Word.Application"); ``` 3. 检查Word是否已启动,如果没有,使用`QAxObject::querySubObject()`打开文档: ```cpp bool isRunning = wordApp->property("IsRunning").toBool(); if (!isRunning) { wordApp->control("Documents.Open", "", "C:\\path\\to\\your\\document.docx"); } ``` 4. 获取Word文档的页眉和页脚部分: ```cpp QObject* headerFooter = wordApp->querySubObject("ActiveDocument.Range.HeadersFooters[Default]"); ``` 5. 设置页码。假设你想要在页脚添加当前页码,你可以创建一个`QAxAction`来插入页码: ```cpp QAction* insertPageNumberAction = new QAction(this); connect(insertPageNumberAction, &QAction::triggered, [headerFooter] { QString pageNumFormat = "页码"; // 格式字符串,例如 "[page]" CComVariant pageNumber; pageNumber.vt = VT_I4; // 假设页码为整数 pageNumber.lVal = qulonglong(pageHeaderFooter->CurrentPage); // 当前页码 headerFooter->Run("InsertField", "&Page", pageNumber, false); }); ``` 6. 调用`insertPageNumberAction->trigger()`来插入页码。 注意这只是一个基本示例,实际操作可能需要处理错误、异常以及不同版本的Word之间的差异。另外,在生产环境中,推荐使用更安全的方式,比如COM事件驱动模型。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值