最近参加了一个比赛,需要生成一份word报告,查找了很多篇相关博客,都不太便于理解,最终还是非常坎坷的给整了出来,今天就详细的梳理下流程。
主要分四个部分
1-首先创建一个word模板
.doc/.docx都行,我建的是test.doc
word模板的部分截图(记住这个景气指数),最后我们会更改这个图片和文字,而格式和其他设置会跟原模板一模一样
1-1另存为.xml格式
1-2把test.xml文件保存在idea的templates目录下,改后缀为.ftl
1-3分析test.ftl文件
首先:test.ftl的内容是压缩的,我们使用Ctrl+Alt+F来格式化代码,接着看下图
有错字=-=,总之就是Ctrl+F 查找 pkg:binaryData,这里存放着图片的字节码,然后点击左边的小标记,隐藏他(太多了),最后我们更换图片就是修改字节码,这里有十几张图片如何辨别我们想要修改的那个呢? 我们继续往下看:
隐藏完后的样子:
然后往上捣:
现在捣到了这个位置:
rid9在这个地方被引用了,那么我就可以认为,我检索的那张图片,就是被放到了这个位置(事实也正是这样)
这里截图错了,应该截到image2.jpeg(意思到了就行)
2-示例代码
2-1导入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
2-2controller层
@GetMapping ("/getWord")
public void exportSellPlan(HttpServletRequest request, HttpServletResponse response) {
System.out.println("节点");
service.exportSellPlan(request, response);
}
2-3service层
map里的键值对可以插入到test.ftl中,以做替换使用
public void exportSellPlan(HttpServletRequest request, HttpServletResponse response){
String imagePath ="src/main/resources/images/11.png";
String imagePath2="src/main/resources/images/面码.jpg";
String imagePath3="src/main/resources/images/favicon.ico";
//获得数据
Map<String, Object> map = new HashMap<>();
map.put("title", "浅喜的果园");
map.put("context", "users");
map.put("context1",this.getImageBase(imagePath));//获取图片的字节码
map.put("mm", this.getImageBase(imagePath2));
map.put("favicon", this.getImageBase(imagePath3));
try {
WordUtil.exportMillCertificateWord(request, response, map, "test", "test.ftl");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// return new CommonResult<>(404,"failure");
}
// return new CommonResult<>(200,"success");
}
//获得图片的base64码
@SuppressWarnings("deprecation")
public String getImageBase(String src) {
if(src==null||src==""){
return "";
}
File file = new File(src);
if(!file.exists()) {
return "";
}
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
assert in != null;
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
3-编辑test.ftl模板
这是我们service层中的map:
map.put(“title”, “浅喜的果园”);
map.put(“context”, “users”);
map.put(“context1”,this.getImageBase(imagePath));//获取图片的字节码
map.put(“mm”, this.getImageBase(imagePath2));
map.put(“favicon”, this.getImageBase(imagePath3));
同时把“景气指数”也替换掉
4-测试结果
启动我们的项目
在浏览器访问http://localhost:8082/getWord
保存这个word文档到本地
查看:
虽然中间有点小差错,不过没啥答问题。