这篇文章在原博客上加上了一些原博主没有写出的一些细节访问的东西,(间接抄袭.......)

原博客 :http://blog.csdn.net/zhangfuliang123/article/details/53413477

这个操作是利用 word模板(.dot)和书签进行操作 .所以,在运行此代码前,先制作好对应的模板,模板中设定好书签.

书签 的主要作用就是使用该程序的时候可以去搜索并且替换调书签位置的内容.以达到批量生成的目的;

看我测试的时候使用的模板

(设置书签:选择你要设置的文本,然后点下 word文档中的插入下面的书签就可以了)

主要方法

1、根据报告要求,设计word模板,定义好需要插入数据的标签,调好其他固定内容的格式。(以保证数据插入后文档内容排列有序)

2、编写word操作接口类,主要包括:打开、关闭、保存、插入文本、插入图片、插入表格、相关格式调整函数

3、编写生成报告界面类,调用接口函数生成word文档。

二、接口函数

WordEngine.h文件

#ifndef WORDENGINE_H
#define WORDENGINE_H
#include <QObject>
#include <QAxObject>
#include <QtCore>class WordEngine : public QObject
{Q_OBJECT
public:explicit WordEngine(QObject *parent = 0);//WordEngine();~WordEngine();/// 打开Word文件,如果sFile路径为空或错误,则打开新的Word文档bool Open(QString sFile, bool bVisible = true);void save(QString sSavePath);void close(bool bSave = true);bool replaceText(QString sLabel,QString sText);bool replacePic(QString sLabel,QString sFile);//插入一个几行几列表格
//    QAxObject *insertTable(QString sLabel,int row,int column);//插入一个几行几列表格 并设置表头QAxObject *insertTable(QString sLabel,int row,int column,QStringList headList);QAxObject *insertTable(QString sLabel,int column,QList<QStringList> headList);//设置列宽void setColumnWidth(QAxObject *table,int column, int width);void SetTableCellString(QAxObject *table, int row,int column,QString text);
signals:public slots:private:QAxObject *m_pWord;      //指向整个Word应用程序QAxObject *m_pWorkDocuments;  //指向文档集,Word有很多文档QAxObject *m_pWorkDocument;   //指向m_sFile对应的文档,就是要操作的文档QString m_sFile;bool m_bIsOpen;bool m_bNewFile;
};#endif // WORDENGINE_H

WordEngine.cpp文件

#include "wordengine.h"
#include "WordEngine.h"
#include "qt_windows.h"WordEngine::WordEngine(QObject *parent) : QObject(parent)
{m_pWord = NULL;m_pWorkDocuments = NULL;m_pWorkDocument = NULL;m_bIsOpen = false;m_bNewFile = false;HRESULT result = OleInitialize(0);if (result != S_OK && result != S_FALSE){qDebug()<<QString("Could not initialize OLE (error %x)").arg((unsigned int)result);}
}WordEngine::~WordEngine()
{//if(m_bIsOpen)//    close();OleUninitialize();
}bool WordEngine::Open(QString sFile, bool bVisible)
{//新建一个word应用程序m_pWord = new QAxObject();bool bFlag = m_pWord->setControl( "word.Application" );if(!bFlag){return false;}m_pWord->setProperty("Visible", bVisible);//获取所有的工作文档QAxObject *document = m_pWord->querySubObject("Documents");if(!document){return false;}//以文件template.dot为模版新建一个文档document->dynamicCall("Add(QString)", sFile);//获取当前激活的文档m_pWorkDocument = m_pWord->querySubObject("ActiveDocument");if(m_pWorkDocument)m_bIsOpen = true;elsem_bIsOpen = false;return m_bIsOpen;
}void WordEngine::save(QString sSavePath)
{if(m_bIsOpen && m_pWorkDocument){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);m_pWorkDocument->dynamicCall("SaveAs (const QString&)", sSavePath);}}qDebug()<<"save Done.";
}void WordEngine::close(bool bSave)
{if(bSave){//save();}if(m_pWord){m_pWord->setProperty("DisplayAlerts", true);}if(m_pWorkDocument){m_pWorkDocument->dynamicCall("Close(bool)", true);}if(m_pWord){m_pWord->dynamicCall("Quit()");}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;}bool WordEngine::replaceText(QString sLabel,QString sText)
{if(!m_pWorkDocument){return false;}//获取文档中名字为sLabel的标签QAxObject *pBookmark = m_pWorkDocument->querySubObject("Bookmarks(QString)",sLabel);if(pBookmark){pBookmark->dynamicCall("Select(void)");pBookmark->querySubObject("Range")->setProperty("Text",sText);delete pBookmark;}return true;
}bool WordEngine::replacePic(QString sLabel,QString sFile)
{if(!m_pWorkDocument)return false;QAxObject *bookmark_pic = m_pWorkDocument->querySubObject("Bookmarks(QString)",sLabel);if(bookmark_pic){bookmark_pic->dynamicCall("Select(void)");QAxObject *Inlineshapes = m_pWorkDocument->querySubObject("InlineShapes");Inlineshapes->dynamicCall("AddPicture(const QString&)",sFile);delete Inlineshapes;}return true;
}//QAxObject *WordEngine::insertTable(QString sLabel, int row, int column)
//{
//     QAxObject *bookmark = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", sLabel);
//     if(bookmark)
//     {
//       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->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.toLocal8Bit().constData());
//           borders->dynamicCall("SetLineStyle(int)",1);
//       }
//       return table;
//     }
//     return NULL;
//}QAxObject *WordEngine::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.toLocal8Bit().constData());borders->dynamicCall("SetLineStyle(int)",1);}return table;}return NULL;
}
/*** @brief WordEngine::insertTable* @param sLabel 模板中的标签* @param column 某行最长列* @param headList 数据 里面存放这每一行的数据* @return*/
QAxObject *WordEngine::insertTable(QString sLabel,  int column, QList<QStringList> headList)
{QAxObject *bookmark = m_pWorkDocument->querySubObject("Bookmarks(QVariant)", sLabel);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(),headList.size(),column);//表格自动拉伸列 0固定  1根据内容调整  2 根据窗口调整table->dynamicCall("AutoFitBehavior(WdAutoFitBehavior)", 2);//设置表头和数据for(int i=0;i<headList.size();i++){QStringList columnList=headList.at(i);for(int j=0;j<columnList.size();j++){table->querySubObject("Cell(int,int)",i+1,j+1)->querySubObject("Range")->dynamicCall("SetText(QString)", columnList.at(j));//加粗table->querySubObject("Cell(int,int)",1,j+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.toLocal8Bit().constData());borders->dynamicCall("SetLineStyle(int)",1);}return table;}return NULL;
}void WordEngine::setColumnWidth(QAxObject *table, int column, int width)
{if(!table){return;}table->querySubObject("Columns(int)",column)->setProperty("Width",width);
}void WordEngine::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);
}

嗯,对原博主的代码做了一些修改,比如插入表格里面的数据.等等.....

我的测试方法:

void test(){WordEngine *w=new WordEngine();w->Open("e://b.doc",false);
//    w->replaceText("a","test");w->replacePic("a","D:/q.jpg");QStringList list;list.append("1");list.append("2");list.append("3");list.append("4");QStringList list2;list2.append("5");list2.append("6");list2.append("7");list2.append("8");QList<QStringList> l1;l1.append(list);l1.append(list2);w->insertTable("b",4,l1);w->save("e://a.doc");w->close();
}

'

然后按照原博主的一步一步来,就会发现报错了.这里还有一个坑,就是得在.pro 文件中加入

QT +=  axcontainer

然后如果还报错就 qmake一下.

还有,这种方式首先本地得安装好 word文档, 记得检查本地的word文档是否安装正确,注册表是否没出问题..

个人觉得这种方式缺陷很大....

the end;

QT 生成word文档相关推荐

  1. Qt使用html生成word文档

    Qt使用html生成word文档 零.前言 一.效果图 二.核心代码 零.前言 项目中要用到把一些图片和一些报告保存为word文件,今天研究了一下,主要是使用html方法保存为word文档,这对htm ...

  2. Qt 使用WPS或HTML生成word文档

    目录 1.使用HTML生成word文档 2.使用WPS 3.实际展示: 1.使用HTML生成word文档 直接使用QString保存HTML语句,在需要插入数据的地方填充,插入表格地方可循坏拼接字符串 ...

  3. android 生成多个表单,Android根据word模板文档将表单数据生成word文档的方案整理...

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 尝试的方案包括以下几种: freemarker 只能在java项目上运行,无法在Android项目上运行: poi 解析doc文件可 ...

  4. php导出doc文件_PHP生成Word文档的方法

    PHP生成Word文档的方法 首先,请确保在你的Windows系统中已经安装并配置好了一个典型的WAMP环境.由于Interop纯粹是一个Windows的特性,我们将在Windows平台下搭建Apac ...

  5. php 内容自动生成word文档,php生成word文档的例子

    /** * 生成word文档 * * @param string $html 内容部分 * @param string $file 文件名称 * @param string $code 当前文件编码, ...

  6. 将HTML导出生成word文档

    前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...

  7. 用Aspose.Words for .NET动态生成word文档中的图片或水印

    1.概述 在项目中生成word文档,这个功能很普遍的,一般生成都是纯文字或是列表的比较多,便于客户打印,而要把图片也生成到word文档中的需求有些客户也是需要的,例如产品图片.这次我们介绍的是如何利用 ...

  8. QT读取Word文档

    Word文档读取 开发工具与关键技术:QtCreator.C++ 作者:何任贤 撰写时间:2020年06月02日 Word文档读取 我们先要在工程文件加入 QT += axcontainer 我们要用 ...

  9. python读取word指定内容_python解析html提取数据,并生成word文档实例解析

    简介 今天试着用ptyhon做了一个抓取网页内容,并生成word文档的功能,功能很简单,做一下记录以备以后用到. 生成word用到了第三方组件python-docx,所以先进行第三方组件的安装.由于w ...

最新文章

  1. Python自动化运维之5、内置函数
  2. CuteEditor 4.0.7研究
  3. 数据挖掘十大经典算法之——Apriori 算法
  4. 多线程学习(三)----死锁问题
  5. LeetCode 1564. 把箱子放进仓库里 I(排序)
  6. java自定义表单_JSP实现用于自动生成表单标签html代码的自定义表单标签
  7. 【数据分析学习】016-numpy数据结构
  8. RN listView使用
  9. 人人网普通登录源码爬取
  10. 关于计算机软件的研究生就业,计算机软件与理论研究生毕业就业方向
  11. 深度学习第一章(rnn)
  12. ct是计算机软件分析报告吗,ct影像工作站|ct诊断报告系统|ct图文工作站|dicom软件系统|技易科技-医学影像软件网...
  13. DS1302时钟(电子钟)
  14. html页面在ie上不兼容,四招解决IE 11浏览器网页不兼容问题
  15. 奥比中光深度相机ros2 humble版安装分享
  16. 一封来自前ThoughtWorks总监咨询师、致国内程序员的一封信
  17. Jenkins设置Window编译环境从节点
  18. FPGA基础知识2(Xilinx Altera FPGA中的逻辑资源 --Slices VS LE比较)
  19. 自学Java半年,没有包装简历,成功找到工作!!个人经验分享
  20. java+vue下载xls文件到本地

热门文章

  1. delphi 复制到剪贴板_Delphi中的基本剪贴板操作(剪切/复制/粘贴)
  2. nginx安装rewrite模块
  3. 树莓派安装Python-OpenCV
  4. @available 和 #available的用法
  5. CannotGetJdbcConnectionException: Could not get JDBC Connection;SQLNestedException:create JDBC drive
  6. ubuntu添加freeradius字典dictionary
  7. 2023年租房投影仪推荐,出租屋投影仪值得买吗?又该怎么选择?
  8. VS2003 安装错误
  9. 竞价账户结构的5要素
  10. PCI-E SSD、M2 SSD、SATA SSD测试