参考博客:https://blog.youkuaiyun.com/yz357823669/article/details/80840855
需求:需要导出的字段
c
o
n
t
e
n
t
是
前
台
用
U
e
d
i
t
o
r
编
译
器
编
译
后
存
入
数
据
库
的
,
是
一
段
h
t
m
l
格
式
的
字
符
串
,
含
有
图
片
。
现
在
要
求
将
编
译
的
文
本
导
出
成
w
o
r
d
格
式
。
心
得
:
1
、
先
用
w
o
r
d
2003
编
译
模
板
,
包
括
样
式
以
及
需
要
替
换
的
数
据
用
{content}是前台用Ueditor编译器编译后存入数据库的,是一段html格式的字符串,含有图片。现在要求将编译的文本导出成word格式。 心得:1、先用word2003编译模板,包括样式以及需要替换的数据用
content是前台用Ueditor编译器编译后存入数据库的,是一段html格式的字符串,含有图片。现在要求将编译的文本导出成word格式。心得:1、先用word2003编译模板,包括样式以及需要替换的数据用{}做占位符。
2、此时设置word的编码格式为utf-8。具体怎么设置问度娘
3、将word文档另存为单个文件网页(.mht)格式。用idea或者nopiad++打开。
4、全文搜索替换gb2312改成utf-8,同时需要加上3D前缀
<meta http-equiv=3DContent-Type content=3D"text/html; charset=3Dutf-8">和Content-Type: text/html; charset=3D"utf-8"
5、处理富文本图片
加上
i
m
a
g
e
s
B
a
s
e
64
S
t
r
i
n
g
!
"
"
这
个
是
图
片
经
过
后
台
处
理
转
为
b
a
s
e
64
码
之
后
的
数
据
尾
部
加
上
{imagesBase64String!""} 这个是图片经过后台处理转为base64码之后的数据 尾部加上
imagesBase64String!""这个是图片经过后台处理转为base64码之后的数据尾部加上{imagesXmlHrefString!""} 这个是引用图片的路径 也是通过后台得到
注意:这两部分的图片名称一定要一样,否则报错打不开
6、记录file:///C:/D1745AB2/test2.files/header.htm 内容(后续会用到)
记录01D40A22.6DCACC80 后面会用到
7、后台处理模板
if(“content”.equals(key)){//处理富文本
RichHtmlHandler handler = new RichHtmlHandler(val.toString());
handler.setDocSrcLocationPrex(“file:///C:/D1745AB2”);//用到前面mht文件中的值
handler.setDocSrcParent(“test2.files”);//用到前面mht文件中的值
handler.setNextPartId(“01D40A22.6DCACC80”);//用到前面mht文件中的值
handler.setShapeidPrex("_x56fe__x7247__x0020");
handler.setSpidPrex("_x0000_i");
handler.setTypeid("#_x0000_t75");
handler.handledHtml(false);
String bodyBlock = handler.getHandledDocBodyBlock();
System.out.println("bodyBlock:\n"+bodyBlock);
String handledBase64Block = "";
if (handler.getDocBase64BlockResults() != null
&& handler.getDocBase64BlockResults().size() > 0) {
for (String item : handler.getDocBase64BlockResults()) {
handledBase64Block += item + "\n";
}
}
if(StringUtils.isBlank(handledBase64Block)){
handledBase64Block = "";
}
res.put("imagesBase64String", handledBase64Block);
String xmlimaHref = "";
if (handler.getXmlImgRefs() != null
&& handler.getXmlImgRefs().size() > 0) {
for (String item : handler.getXmlImgRefs()) {
xmlimaHref += item + "\n";
}
}
if(StringUtils.isBlank(xmlimaHref)){
xmlimaHref = "";
}
res.put("imagesXmlHrefString", xmlimaHref);
res.put("content", bodyBlock);
}
8、然后通过提供的三个工具类RichHtmlHandler WordHtmlGeneratorHelper WordImageConvertor 就可以了
工具类去参考的博客中下载
注意事项:1、图片路径可能找不到,尽量用绝对路径。
2、可能会遇到单个文件网页打不开的情况这个时候检查模板是否有字段与后台不匹配,或者是否有空值的现象。
3、如果一个字段中包含多个图片,后台存为list集合,前台用<#list></#list>标签进行循环输出
4、模板上的图片被三个地方用到,一个是base64码模块,一个是图片的样式模块,一个是底部引用模块。
在此 感谢恩人