Qt-QAxObject类-导出为word文件

2023-10-25 03:59
文章标签 qt 导出 word qaxobject

本文主要是介绍Qt-QAxObject类-导出为word文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • 简介
  • 代码实现
  • 常见问题解决
    • 1、QAxObject对象在子线程中连接失败
    • 2、添加QAxObject头文件后编译报错:“无法打开源文件”
    • 3、修改单元格属性后未生效
  • 常见属性

简介

  • 本文主要介绍QAxObject类导出为word文件操作。以实现导出一份成绩单为例,介绍可能会出现的问题,如何去解决。同时会将word中常用的一些属性枚举封装为函数进行介绍,方便读者理解。

代码实现

  • 代码分析详见注释
  • custome_output_file_service.h
#pragma once
#include <QObject>
#include <QAxObject>
#include <QTextCodec>
#include <QDateTime>
#include <QDebug>
#include "custome_output_file_global.h"class CustomeOutputFileService:public ICustomeOutputFile
{
public:CustomeOutputFileService();~CustomeOutputFileService();virtual bool CreateRecordWord(CyCString _path);virtual bool SetRecordInformation(CyCString _name, int _count);virtual bool InsertRecordData(vector<std::string> _data);virtual bool Close();private:QAxObject *		word_;QAxObject *		act_doc_;QString			file_path_;int				count_;QAxObject*		simulation_table_;
};
  • custome_output_file_service.cpp
#include "custome_output_file_service.h"
#include "qt_windows.h"CustomeOutputFileService::CustomeOutputFileService():count_(2)
{
}CustomeOutputFileService::~CustomeOutputFileService()
{
}bool CustomeOutputFileService::CreateRecordWord(CyCString _path)
{file_path_ = StdString2QString(_path);count_ = 2;//因为COM是在GUI线程初始化和销毁的,在新开的线程里面并没有初始化,所以得自己初始化。HRESULT r_com = OleInitialize(0);if (r_com != S_OK && r_com != S_FALSE){qDebug("Qt: Could not initialize OLE (error %x)",(unsigned int)r_com);}//创建word文档//指向整个word应用程序word_ = new QAxObject();if (!word_->setControl("word.Application"))return false;word_->setProperty("Visible", false);QAxObject *documents = word_->querySubObject("Documents");if (!documents)return false;documents->dynamicCall("Add(void)");//获取当前激活的文档act_doc_ = word_->querySubObject("ActiveDocument");if (act_doc_ == nullptr)return false;QAxObject* selection = word_->querySubObject("Selection");selection->querySubObject("Font")->setProperty("Size", 11);selection->dynamicCall("TypeText(const QString&)", "");return true;
}bool CustomeOutputFileService::SetRecordInformation(CyCString _name, int _count)
{//当前日期QDateTime cur_data_time = QDateTime::currentDateTime();QString data_time = cur_data_time.toString("yyyy-MM-dd hh:mm:ss");//设置标题风格及内容QAxObject* selection = word_->querySubObject("Selection");selection->querySubObject("Font")->setProperty("Size", 14);selection->querySubObject("Font")->setProperty("Bold", true);selection->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");selection->dynamicCall("TypeText(const QString&)", QStringLiteral("成绩单\n"));//设置成绩单信息风格及内容selection->querySubObject("Font")->setProperty("Size", 11);selection->querySubObject("Font")->setProperty("Bold", false);selection->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphLeft");selection->dynamicCall("TypeText(const QString&)", QStringLiteral("教师:%1 日期:%2\n").arg(StdString2QString(_name)).arg(data_time));//设置数据内容格式QAxObject* tables = act_doc_->querySubObject("Tables");QAxObject* range = selection->querySubObject("Range");simulation_table_ = tables->querySubObject("Add(QAxObject*, int, int)", range->asVariant(), _count + 1, 6);QAxObject* border_line1 = simulation_table_->querySubObject("Borders(1)");border_line1->dynamicCall("SetLineStyle(int)", 1);QAxObject* border_line2 = simulation_table_->querySubObject("Borders(2)");border_line2->dynamicCall("SetLineStyle(int)", 1);QAxObject* border_line3 = simulation_table_->querySubObject("Borders(3)");border_line3->dynamicCall("SetLineStyle(int)", 1);QAxObject* border_line4 = simulation_table_->querySubObject("Borders(4)");border_line4->dynamicCall("SetLineStyle(int)", 1);QAxObject* border_line5 = simulation_table_->querySubObject("Borders(5)");border_line5->dynamicCall("SetLineStyle(int)", 1);QAxObject* border_line6 = simulation_table_->querySubObject("Borders(6)");border_line6->dynamicCall("SetLineStyle(int)", 1);QAxObject* trange = simulation_table_->querySubObject("Range");trange->querySubObject("ParagraphFormat")->setProperty("Alignment", "wdAlignParagraphCenter");trange->querySubObject("Cells")->setProperty("VerticalAlignment", "wdCellAlignVerticalCenter");selection->querySubObject("Font")->setProperty("Bold", true);simulation_table_->querySubObject("Cell(int, int)", 1, 1)->querySubObject("Range")->dynamicCall("SetText(QString)", QStringLiteral("姓名"));simulation_table_->querySubObject("Cell(int, int)", 1, 2)->querySubObject("Range")->dynamicCall("SetText(QString)", QStringLiteral("学号"));simulation_table_->querySubObject("Cell(int, int)", 1, 3)->querySubObject("Range")->dynamicCall("SetText(QString)", QStringLiteral("班级"));simulation_table_->querySubObject("Cell(int, int)", 1, 4)->querySubObject("Range")->dynamicCall("SetText(QString)", QStringLiteral("实验场次"));simulation_table_->querySubObject("Cell(int, int)", 1, 5)->querySubObject("Range")->dynamicCall("SetText(QString)", QStringLiteral("成绩"));simulation_table_->querySubObject("Cell(int, int)", 1, 6)->querySubObject("Range")->dynamicCall("SetText(QString)", QStringLiteral("评语"));return true;
}//插入数据
bool CustomeOutputFileService::InsertRecordData(vector<std::string> _data)
{if (_data.size() == 0){return false;}for (int i = 0; i < _data.size(); ++i){simulation_table_->dynamicCall("AutoFitBehavior(int)", 6);simulation_table_->querySubObject("Rows(int)", count_)->setProperty("Height", 20);simulation_table_->querySubObject("Cell(int, int)", count_, i + 1)->querySubObject("Range")->dynamicCall("SetText(QString)", StdString2QString(_data.at(i)));}count_++;return true;
}//关闭连接
bool CustomeOutputFileService::Close()
{act_doc_->dynamicCall("SaveAs (const QString&)", file_path_);act_doc_->dynamicCall("Close(bool)", true);word_->dynamicCall("Quit()");//关闭COMOleUninitialize();return true;
}

常见问题解决

1、QAxObject对象在子线程中连接失败

 word_->setControl("word.Application")
  1. 连接对象为QAxWidget类对象,GUI相关对象不能在子线程中进行操作,所以应该修改为QAxObject类对象。
  2. 如果对象为QAxObject类对象还是连接失败,则查看COM是否在子线程初始化,如果没有添加如下代码
//因为COM是在GUI线程初始化和销毁的,在新开的线程里面并没有初始化,所以得自己初始化。HRESULT r_com = OleInitialize(0);if (r_com != S_OK && r_com != S_FALSE){qDebug("Qt: Could not initialize OLE (error %x)",(unsigned int)r_com);}

2、添加QAxObject头文件后编译报错:“无法打开源文件”

  • 原因在于当前工程中并没有包含相应的模块,需要到项目属性设置中添加相应模块,并添加相应附加包含目录和附加依赖项。如下图所示:
    在这里插入图片描述

3、修改单元格属性后未生效

  1. 查看设置单元格为全局还是特定单元格。
  2. 是否设置属性后再插入数据。
  3. 属性字段是否正确。
  4. 单元格对象是否添加。

常见属性

  • 以下是一些word中表格常用的一些属性( QAxObject* selection_ = m_pWord->querySubObject(“Selection”);)
/** 排版方式* 纵行、横行
*/selection_->querySubObject("PageSetup")->setProperty("Orientation","wdOrientLandscape");    //纵selection_->querySubObject("PageSetup")->setProperty("Orientation","wdOrientPortrait");     //横
/** 获取页宽
*/int width_;width_ = selection_->querySubObject("PageSetup")->property("PageWidth").toInt();;
/**设置字号
*/selection_->querySubObject("Font")->setProperty("Size",14);
/**设置对齐方式
*/selection_->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphCenter");    //居中对齐selection_->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphJustify");   //分散对齐selection_->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphRight");     //右对齐selection_->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphLeft");      //左对齐
/**插入文字
*/
selection_->dynamicCall("TypeText(const QString&)","hello world!");
/**插入图片
*/QString filename = file;filename.replace("/","\\");     //转义字符替换QAxObject *Inlineshapes = selection_->querySubObject("InlineShapes");Inlineshapes->dynamicCall("AddPicture(const QString&)",filename);delete Inlineshapes;
/**插入回车
*/
selection_->dynamicCall("TypeParagraph(void)");
/** 光标移到末尾,跳出单元格
*/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 head_list)
{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)", head_list.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
*/selection->dynamicCall("MoveRight(int)",1);

以上是对QAxObject导出word文档表格的一些简单操作,新人第一次发博客,如果此文帮助到你( •̀ ω •́ )✧,动动小手点个赞可好O(∩_∩)O。
原创文章,转载请标明本文出处。

这篇关于Qt-QAxObject类-导出为word文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/279881

相关文章

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach

Qt QCustomPlot库简介(最新推荐)

《QtQCustomPlot库简介(最新推荐)》QCustomPlot是一款基于Qt的高性能C++绘图库,专为二维数据可视化设计,它具有轻量级、实时处理百万级数据和多图层支持等特点,适用于科学计算、... 目录核心特性概览核心组件解析1.绘图核心 (QCustomPlot类)2.数据容器 (QCPDataC

Qt如何实现文本编辑器光标高亮技术

《Qt如何实现文本编辑器光标高亮技术》这篇文章主要为大家详细介绍了Qt如何实现文本编辑器光标高亮技术,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录实现代码函数作用概述代码详解 + 注释使用 QTextEdit 的高亮技术(重点)总结用到的关键技术点应用场景举例示例优化建议

Qt 设置软件版本信息的实现

《Qt设置软件版本信息的实现》本文介绍了Qt项目中设置版本信息的三种常用方法,包括.pro文件和version.rc配置、CMakeLists.txt与version.h.in结合,具有一定的参考... 目录在运行程序期间设置版本信息可以参考VS在 QT 中设置软件版本信息的几种方法方法一:通过 .pro

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

VS配置好Qt环境之后但无法打开ui界面的问题解决

《VS配置好Qt环境之后但无法打开ui界面的问题解决》本文主要介绍了VS配置好Qt环境之后但无法打开ui界面的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目UKeLvb录找到Qt安装目录中designer.UKeLvBexe的路径找到vs中的解决方案资源

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

Mac备忘录怎么导出/备份和云同步? Mac备忘录使用技巧

《Mac备忘录怎么导出/备份和云同步?Mac备忘录使用技巧》备忘录作为iOS里简单而又不可或缺的一个系统应用,上手容易,可以满足我们日常生活中各种记录的需求,今天我们就来看看Mac备忘录的导出、... 「备忘录」是 MAC 上的一款常用应用,它可以帮助我们捕捉灵感、记录待办事项或保存重要信息。为了便于在不同

如何Python使用设置word的页边距

《如何Python使用设置word的页边距》在编写或处理Word文档的过程中,页边距是一个不可忽视的排版要素,本文将介绍如何使用Python设置Word文档中各个节的页边距,需要的可以参考下... 目录操作步骤代码示例页边距单位说明应用场景与高级用China编程途小结在编写或处理Word文档的过程中,页边距是一个