Qt 导出word

前言

qt导出可以利用QAxObject去导出word或者excel等。
QAxObject主要是调用QAxObject的 querySubObject、dynamicCall、setProperty等方法,其中方法的参数属性,可以通过word官网查询,具体属性怎么用,暂时也没找到有相应文档,有需要可以结合office官方文档属性和下面分享的或者网上找下资料的,依葫芦画瓢,找规律试一试。
在这里插入图片描述
下面分享导出word的一些常用属性。

Test案例

首先在.pro文件中需要加入:QT += axcontainer
使用时加头文件

#include <QAxObject>

不多bb直接上代码
.cpp文件

#include "widget.h"
#include "ui_widget.h"
#include <QAxObject>
#include <QFile>
#include <QMap>
#include <QDebug>
#include <QFileDialog>
#include <QPushButton>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    QAxObject* m_wordWidget = new QAxObject();
    bool flag = m_wordWidget->setControl("Word.Application");//初始化COM对象,新建一个word应用程序
    if(!flag)
    {
        flag = m_wordWidget->setControl("kwps.Application");//尝试用wps打开
        if(!flag)
            return;
    }

    m_wordWidget->setProperty("Visible", true);//设置为可见,false 则不会在界面打开显示

    QAxObject* documents = m_wordWidget->querySubObject("Documents");//获取所有的工作文档(返回一个指向QAxObject包含的COM对象)
    if(!documents)
        return ;

    //法 一
//    QString filePathDot = "D:/qt-test/word/Doc1.dot";
//    QFile file(filePathDot);
//    if(file.exists())
//        documents->dynamicCall("Add(const QString&)",filePathDot);//以Doc1.dot新建一个
//    else
//        return ;
     //法二
    QString filePathDocx = "D:/qt-test/word/test.docx";
    QFile file(filePathDocx);
    if(file.exists())
        documents->dynamicCall("Open(const QString&)",filePathDocx);//直接打开一个空文档
    else
        return;
    //上面描述的方法,都必须要在先创建一个文档


    QAxObject *activeDocument = m_wordWidget->querySubObject("ActiveDocument");//获取当前激活的文档

//    //读取word中的文字
//    QAxObject* pRange = activeDocument->querySubObject("Range()");
//   if (NULL != pRange)
//   {
//       QString text = pRange->property("Text").toString();
//       qDebug()<<"read:"<<text;
//       delete pRange;
//       pRange = NULL;
//   }

   //插入文字
    QAxObject* selection  = m_wordWidget->querySubObject("Selection");
    if(!selection)
        return;

    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleTitle");//设置标题
    selection->querySubObject("Font")->setProperty("Name","微软雅黑");//设置字体
    selection->querySubObject("Font")->setProperty("Size",20);//设置字体大小
    //selection->querySubObject("Font")->setProperty("Color",0);//设置字体颜色
    selection->dynamicCall("TypeText(const QString&)"," 测试报告");
    selection->dynamicCall("TypeParagraph(void)");//插入回车

    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleSubtitle");//设置副标题
    selection->querySubObject("Font")->setProperty("Name","微软雅黑");
    selection->querySubObject("Font")->setProperty("Size",15);
    selection->dynamicCall("TypeText(const QString&)","勒布朗·詹姆斯个人信息");
    selection->dynamicCall("TypeParagraph(void)");


    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleHeading1");//设置标题1
    selection->querySubObject("Font")->setProperty("Name","微软雅黑");
    selection->querySubObject("Font")->setProperty("Size",12);
    selection->dynamicCall("TypeText(const QString&)"," 勒布朗·詹姆斯简介");
    selection->dynamicCall("TypeParagraph(void)");


    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleBodyTextFirstIndent2");//	正文首行缩进
    selection->querySubObject("Font")->setProperty("Name","微软雅黑");
    selection->querySubObject("Font")->setProperty("Size",10);
    selection->dynamicCall("TypeText(const QString&)","勒布朗·詹姆斯(LeBron James),"
    											"全名勒布朗·雷蒙·詹姆斯(LeBron Raymone James),"
                                                "1984年12月30日出生于美国俄亥俄州阿克伦,美国职业篮球运动员,"
                                                "司职小前锋,绰号“小皇帝”,效力于NBA洛杉矶湖人队。");
    selection->dynamicCall("TypeParagraph(void)");


    //插入图片
    QString picPath = "D:/qt-test/word/whoBetter.jpg";
    QAxObject *Inlineshapes = selection->querySubObject("InlineShapes");
    Inlineshapes->dynamicCall("AddPicture(const QString&)",picPath);
    delete Inlineshapes;
    selection->dynamicCall("TypeParagraph(void)");

    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleHeading2");//设置标题2
    selection->querySubObject("Font")->setProperty("Name","微软雅黑");
    selection->querySubObject("Font")->setProperty("Size",12);
    selection->dynamicCall("TypeText(const QString&)"," 主要荣誉");
    selection->dynamicCall("TypeParagraph(void)");


    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleBodyTextFirstIndent2");
    selection->querySubObject("Font")->setProperty("Name","微软雅黑");
    selection->querySubObject("Font")->setProperty("Size",10);
    selection->dynamicCall("TypeText(const QString&)","4届NBA总冠军、NBA总决赛MVP(2012;2013;2016;2020)"
                           "3届NBA全明星正赛MVP(2006;2008;2018)"
                           "2届奥运会金牌(2008,2012)"
                           "2019-20赛季NBA助攻王 [8] "
                           "2007-08赛季NBA得分王"
                           "18届NBA全明星阵容(2005-2022)"
                           "17届NBA最佳阵容(13次一阵,3次二阵,1次三阵)");
    selection->dynamicCall("TypeParagraph(void)");


    selection->dynamicCall("setStyle(WdBuiltinStyle)", "wdStyleHeading3");//设置标题2
    selection->querySubObject("Font")->setProperty("Name","微软雅黑");
    selection->querySubObject("Font")->setProperty("Size",12);
    selection->dynamicCall("TypeText(const QString&)"," 重要事件");
    selection->dynamicCall("TypeParagraph(void)");

    QStringList headList;
    headList<<"时间"<<"事件";

    QMap<int , QString> map;
    map.insert(2003,"2003年NBA选秀状元");
    map.insert(2010,"2010年加盟迈阿密热火队");
    map.insert(2014,"2014年重回克利夫兰骑士队");
    map.insert(2016,"2016年夺得克利夫兰骑士队首冠");
    map.insert(2018,"2018年加盟洛杉矶湖人队");

    //插入表格
    QAxObject *range = selection->querySubObject("Range");
    QAxObject *tables = activeDocument->querySubObject("Tables");
    QAxObject *table = tables->querySubObject("Add(QVariant,int,int)",
    range->asVariant(),map.size()+1,headList.length());//map.size 行

    table->setProperty("Style","网格型");
    table->dynamicCall("AutoFitBehavior(WdAutoFitBehavior)", 2);//表格自动拉伸列 0固定  1根据内容调整  2 根据窗口调整

    //设置表头
    for(int i=0;i<headList.size();i++)
    {
        table->querySubObject("Cell(Long,Long)",1,i+1)->querySubObject("Range")
            ->querySubObject("Shading")
            ->dynamicCall("BackgroundPatternColorIndex", "wdDarkBlue");//设置表格底色

        table->querySubObject("Cell(Long,Long)",1,i+1)->querySubObject("Range")
                ->querySubObject("ParagraphFormat")
                ->dynamicCall("Alignment", "wdAlignParagraphCenter");//设置表格居中

        table->querySubObject("Cell(Long,Long)",1,i+1)->querySubObject("Range")
        ->dynamicCall("SetText(QString)", headList.at(i));//设置表格内容
        table->querySubObject("Cell(Long,Long)",1,i+1)->querySubObject("Range")
        ->dynamicCall("SetBold(int)", true);//加粗
    }

    //填充表格
    QMap<int , QString>::iterator itor = map.begin();
    for (int j=0; itor != map.end(); itor++,j++)
    {
        table->querySubObject("Cell(Long,Long)",j+2,1)->querySubObject("Range")
                ->querySubObject("ParagraphFormat")
                ->dynamicCall("Alignment", "wdAlignParagraphLeft");//居左

        table->querySubObject("Cell(Long,Long)",j+2,1)
        ->querySubObject("Range")->querySubObject("Font")
        ->setProperty("Color","wdColorBlack");//设置字体颜色
        table->querySubObject("Cell(Long,Long)",j+2,1)
        ->querySubObject("Range")->dynamicCall("SetText(QString)", QString::number(itor.key()));


        table->querySubObject("Cell(Long,Long)",j+2,2)->querySubObject("Range")
                ->querySubObject("ParagraphFormat")
                ->dynamicCall("Alignment", "wdAlignParagraphLeft");//居左

        table->querySubObject("Cell(Long,Long)",j+2,2)
        ->querySubObject("Range")->querySubObject("Font")
        ->setProperty("Color","wdColorBlack");//设置字体颜色
        table->querySubObject("Cell(Long,Long)",j+2,2)->querySubObject("Range")
        ->dynamicCall("SetText(QString)", itor.value());
    }

    //跳出表格
    QVariantList params;
    params.append(6);
    params.append(0);
    selection->dynamicCall("EndOf(QVariant&, QVariant&)", params).toInt();

    QString filePath2 = "D:/qt-test/word/test2.docx";
    activeDocument->dynamicCall("SaveAs(const QString&)",
    QDir::toNativeSeparators(filePath2));//保存至filePath2,

}

Widget::~Widget()
{
    delete ui;
}


导出word后

在这里插入图片描述

总结

相应属性可以在office官网 Docs/office VBA/word 找到这里左边可以就可以搜索相应关键字了 。这里以颜色属性为例,这里也直接附上地址, office官方稳定网址
在这里插入图片描述
这里只是简单的实现了标题,副标题,插入文字,表格,图片等。

  • 5
    点赞
  • 104
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
根据提供的引用内容,可以使用Qt的ActiveQt模块来根据模板导出Word文档。在Qt中,可以使用QAxWidget和QAxObject类来实现这个功能。QAxWidget类是一个包装ActiveX控件的QWidget,而QAxObject类则用于与ActiveX对象进行交互。首先,需要在代码中包含相应的头文件,并初始化COM库。然后,可以使用QAxWidget类创建一个Word应用程序对象,并打开指定的模板文件。接下来,可以使用QAxObject类来操作Word文档,例如替换模板中的标签为实际的内容。最后,可以保存并关闭Word文档。具体的代码实现可以参考提供的引用内容中的示例代码。\[1\]\[3\] 需要注意的是,模板文件是以Docx格式的Word文档,并且模板中的标签是以{{开头,以}}结尾的。标签可以出现在任何位置,包括页眉、页脚、表格内部、文本框等。使用表格布局可以设计出优秀专业的文档。同时,推荐使用poi-tl模板,因为它遵循“所见即所得”的设计,可以完全保留模板和标签的样式。\[2\] 总结起来,使用Qt的ActiveQt模块,结合QAxWidget和QAxObject类,可以根据模板导出Word文档。具体的实现可以参考提供的引用内容中的示例代码。 #### 引用[.reference_title] - *1* [QT根据模板文件xxx.dot导出word格式xxx.docx](https://blog.csdn.net/qq_42938320/article/details/101771902)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [java根据模板导出word poi-tl使用Word模板和数据创建Word文档](https://blog.csdn.net/weixin_45003796/article/details/124670299)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Qt导出word报告(QAxObject)](https://blog.csdn.net/LebronBear/article/details/127516721)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值