参考使用开源库github地址:DocxFactory
https://github.com/DocxFactory/DocxFactory
示例word:
转换后word:
参考转换代码:
#pragma comment(lib,"opt/DocxFactory/lib/DocxFactory.lib")
#include "opt/DocxFactory/include/WordProcessingMerger.h"
#include "opt/DocxFactory/include/WordProcessingCompiler.h"
#include <exception>
#include <iostream>
#include <ctime>
#include<Windows.h>
using namespace DocxFactory;
using namespace std;
// 转换文件内容编码格式 只要转换为utf-8即可用什么方法都可!
char* G2U(const char* gb2312)
{
int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
if (wstr) delete[] wstr;
return str;
}
int main()
{
try
{
WordProcessingCompiler& l_compiler =
WordProcessingCompiler::getInstance();
time_t l_start = clock();
l_compiler.compile(
"/tmp/实验报告_模板.docx",
"/tmp/实验报告_模板.dfw");
cout << "Completed (in "
<< (double)(clock() - l_start) / CLOCKS_PER_SEC
<< " seconds)."
<< endl;
}
catch (const exception& p_exception)
{
cout << p_exception.what() << endl;
}
try
{
WordProcessingMerger& l_merger =
WordProcessingMerger::getInstance();
time_t l_start = clock();
l_merger.load(
"/tmp/实验报告_模板.dfw");
//l_merger.setClipboardValue("Account", "Account", "12345678901");
//l_merger.setClipboardValue("Account", "Active", "no");
l_merger.setClipboardValue("", "Name",
G2U("张三"));
l_merger.setClipboardValue("Account", "Gender",
G2U("女"));
l_merger.setClipboardValue("Account", "l1",
G2U("第一列"));
l_merger.setClipboardValue("Account", "l2",
G2U("第二列"));
l_merger.setClipboardValue("Account", "l3",
G2U("第三列"));
l_merger.setClipboardValue("Account", "Test ",
"/tmp/AKAK.jpg");
for (int i = 0; i < 3; i++)
{
// !!!此处第一个参数要为空,否则替换失败,不知道为啥
l_merger.setClipboardValue("", "Content",
G2U("随便测试一下"));
// 可以用paste实现重复替换创建 注意要在全局最后写一旦paste则会影响当前拷贝的模板内容
// 表格内容还是图片都可用用这种方法不再赘述
l_merger.paste("Content");
}
//l_merger.paste("Account");
l_merger.save("/finish/实验报告_模板.docx");
cout << "Completed (in "
<< (double)(clock() - l_start) / CLOCKS_PER_SEC
<< " seconds)."
<< endl;
}
catch (const exception& p_exception)
{
cout << p_exception.what() << endl;
}
}
调用的都是上面git地址的动态库和函数,具体使用英文pdf也有,注意以下几点:
设置书签Account,叫别的也可,必须有一个全局的书签进行全局替换复制,先全选点书签,起名字添加即可,添加成功后点击书签定位可以检查是否都全部选中:
需要拷贝复制替换的添加对对应部分添加书签即可,中间可以添加随意内容,不一定只有替换内容,替换内容用{}括起来就行,不行的话就删了{}重新试一下即可:
需要替换的图片在下图设置,这个替换文字我找了好久,WPS里好像没有,还是得用office: