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 @ 2024-07-23 16:25  BangZeng  阅读(30)  评论(0编辑  收藏  举报