第一步
准备模板
第二步
将模板另存为xml ,在word内另存为,不要手动修改文件后缀,防止乱码
找到图中所示标签 <w:binData> 将标签内base64编码删除(既 /9j/4Q …)
改为${image}
第三步
将xm文件后缀改为 .ftl
第四步
导入jar包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
调用方法
接口调用
String fileName = "个人基本情况";
String mouldName = "basic.ftl";
Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("name","zzq");
dataMap.put("image",WordDataUtil.getImgFileToBase64("D:\\test\\issue\\testwordimage.png"));
wordDataUtil.exportWord(mouldName,dataMap,fileName,response);
工具类如下:
package com.ibbc.web.manager.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
public class WordDataUtil {
/**
mouldName ftl文件名
dataMap 需要填充的map
fileName 导出的word文件名
**/
public void exportWord(String mouldName, Map<String,Object> dataMap, String fileName, HttpServletResponse response) throws IOException{
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File("D:\\test\\ftl")); //FTL文件所存在的位置(文件夹)
Template t = null;
try {
t = configuration.getTemplate(mouldName);
} catch (Exception e) {
e.printStackTrace();
}
String FileName = fileName+".doc";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="+FileName);
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileName)));//文件输出地址
} catch (IOException e) {
e.printStackTrace();
}
try {
t.process(dataMap,out);
} catch (TemplateException e) {
e.printStackTrace();
}
}
//图片转码工具类
public static String getImgFileToBase64(String imgFile){
InputStream inputStream = null;
byte[] buffer = null;
try {
inputStream = new FileInputStream(imgFile);
int count = 0;
while (count == 0){
count = inputStream.available();
}
buffer = new byte[count];
inputStream.read(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new BASE64Encoder().encode(buffer);
}
}