同样需要使用QT += axcontainer
同样需要注意:新建QAXObject,完成操作后需要关闭文档并删除m_pWord指针!
这样word应用程序会在后台自动退出!
#ifndef WORD_H
#define WORD_H
#include <QObject>
#include <QAxObject>
#include <QAxWidget>
class Word : public QObject
{
Q_OBJECT
public:
explicit Word(QObject *parent = nullptr);
~Word();
private:
QString m_fileName;//存入位置
QAxWidget *m_pWord;
QAxObject *m_pDocuments;
QAxObject *m_pDocument;//
const QString dot = "ZYLH1220本安稳压电源老化报告模板.dot";
public:
void createWordDocument();//创建word文档
bool insertText(QString Tag, QString text);//往标签处插入文字
void saveAndQuit(const QString &text);//保存文档并退出
signals:
public slots:
};
#endif // WORD_H
#include "word.h"
#include <QFileDialog>
#include <QDebug>
#include <QCoreApplication>
Word::Word(QObject *parent) : QObject(parent)
{
m_pWord = nullptr;
m_pDocument = nullptr;
}
Word::~Word()
{
}
void Word::createWordDocument()
{
m_pWord = new QAxWidget("Word.Application");//新建一个word应用程序
m_pWord->setProperty("Visible", false);//不显示窗体
QAxObject *pDocuments = m_pWord->querySubObject("Documents");
pDocuments->dynamicCall("Add(Qstring)", QCoreApplication::applicationDirPath() + "/" + dot);//模版目录
m_pDocument = m_pWord->querySubObject("ActiveDocument");//获取当前激活的文档
}
bool Word::insertText(QString Tag, QString text)
{
if (m_pDocument->isNull()) return false;//首先判断有没有获取当前激活的文档,没有则返回失败
QAxObject *pBookMarkCode = m_pDocument->querySubObject("Bookmarks(QVariant)", Tag);//获取指定标签
if (pBookMarkCode)
{
pBookMarkCode->dynamicCall("Start");//选择该指定标签
pBookMarkCode->querySubObject("Range")->setProperty("Text", text);//往标签处插入文字
delete pBookMarkCode;
return true;
}
return false;
}
void Word::saveAndQuit(const QString &text)
{
m_pDocument->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(text));//“/”换成“\”;否则在windows下保存不成功
m_pDocument->dynamicCall("Close()");//关闭
m_pWord->dynamicCall("Quit()");//退出
delete m_pWord;
}
以上代码基于对此文的改进!
原文:提示没有该属性,正确的应该是start;
pBookMarkCode->dynamicCall("Selection");//选择该指定标签
Quit的调用主题应该是m_pWord;
最后delete;