qt 通过wordXml模板替换内容

参考:C++(Qt) 和 Word、Excel、PDF 交互总结 - 个人文章 - SegmentFault 思否

一、步骤:

1.word文件:手动输入或者复制内容进去(复制内容+手动输入 会让word另存为xml内容出现不在一个<w:t>中的问题)

2.word中输入用于替换key内容

3.word.docx//doc另存为word.xml文件

 

4.读取内容进行替换

5.注意:

1.中文进行替换是需要添加QString::fromLocal8Bit("中文");

2.xml格式默认utf8编码

6.结果

 

二、代码

复制代码
#ifndef WORDREPLACEHELPER_H
#define WORDREPLACEHELPER_H

#include<QString>
class WordReplaceHelper
{
public:
    WordReplaceHelper();
    WordReplaceHelper(const QString& strModelFileName); //模板
    void SetModelFile(const QString& strModelFileName);
    void Replace(const QString& strKey,const QString& strValue);
    void WordExport(const QString& strExportFileName);      //文档导出

private:
    QString _xmlContent;
};

#endif // WORDREPLACEHELPER_H
复制代码

 

复制代码
#include "wordreplacehelper.h"

#include <QFile>
#include<QDebug>
WordReplaceHelper::WordReplaceHelper()
{

}

WordReplaceHelper::WordReplaceHelper(const QString &strModelFileName)
{
    SetModelFile(strModelFileName);
}

void WordReplaceHelper::SetModelFile(const QString &strModelFileName)
{
    _xmlContent.clear();
    QFile file(strModelFileName);
    if(!file.exists())
    {
          qDebug() << "xml file not exist. " << file.errorString();
          return;

    }
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "open xxml file fail. " << file.errorString();
        return ;
    }
    QByteArray baContent = file.readAll();
    file.close();
    _xmlContent = QString::fromLocal8Bit(baContent);
}

void WordReplaceHelper::Replace(const QString &strKey, const QString &strValue)
{
    //中文传递进来时需要添加QString::fromLocal8Bit("中文");
    //xml格式默认utf8编码
    _xmlContent.replace(strKey.toUtf8(),strValue.toUtf8());
}

void WordReplaceHelper::WordExport(const QString &strExportFileName)
{
    QFile newFile(strExportFileName);
    if (!newFile.open(QIODevice::WriteOnly))
    {
        qDebug() << "file open fail." << newFile.errorString();;
        return ;
    }

    newFile.write(_xmlContent.toLocal8Bit());
    newFile.close();
}
复制代码

 

posted @   BangZeng  阅读(79)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示