1.首先新建一个带图片的doc
2.另存为xml格式(具体看上一篇)
3.把生成的xml文件进行修改
4.修改后缀为ftl,作为模板文件使用,放到指定位置(我放到了电脑的D盘template文件夹中)
5.后台填充数据
Map<String, Object> data = new HashMap<String, Object>(); //声明map用来存数据
//将具体的数据存到map中,注意,这里的key名称要和模板文件的占位符名称一致
data.put("sfzh", "111111111111111111");
//这里是处理图片
//获取项目的部署路径(因为我的图片在服务器中)
String realPath = request.getSession().getServletContext().getRealPath("/").replace(request.getContextPath().replaceAll("/", ""), "");
String img = null;
InputStream in;
byte[] picdata = null;
try {
//读取图片
in = new FileInputStream(realPath+"images/rl/image_123.jpg");
picdata = new byte[in.available()];
in.read(picdata);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
img = encoder.encode(picdata);
data.put("image", img);
//参数解释(第一个参数是模板文件的名称,第二、三个拼成生成文件的名称(这样文件名就叫文档名称-文档1.doc),第四个是数据map)
WordUtil.word("rqpz.ftl", "文档名称", "文档1", data);
6.另附WordUtil的源码
public class WordUtil {
public static void word(String ftl,String tb,String ryname,Map<String, Object> map) throws TemplateException, IOException{
HttpServletResponse response = ServletActionContext.getResponse();
response.reset();
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//获取模板所在的路径
configuration.setDirectoryForTemplateLoading(new File("D:/template/"));
//以utf-8的编码读取ftl文件
Template t = configuration.getTemplate(ftl,"utf-8");
String fileName = URLEncoder.encode(tb+"-"+ryname,"UTF-8") + ".doc";
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
Writer out1 = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"),10240);
t.process(map, out1);
out1.close();
}
}