用freemarker生成word文档,并插入图片
最近需要做一个问卷功能,要求用户填写完问卷后,后台会生成一个word文档,将用户提交的数据插入到word中。
创建word模板
新建一个word文档,将需要应用的格式固定好
修改好格式后,将word文档保存为XML格式的文件
例:
将word保存为xml格式
将XML中base64格式的图片信息删除掉,改为占位符,如:${image}
如果需要在模板中插入不定数量的图片,要将XML图片格式进行修改,增加<#list imageList as item></#list>.如下:
<#list image as item><w:pict><w:binData w:name=“wordml:// i t e m . i n d e x . p n g " > {item.index}.png"> item.index.png">{item.image_base64}
</w:binData><v:shape id=” i t e m . i n d e x " o : s p t = " 75 " a l t = " {item.index}" o:spt="75" alt=" item.index"o:spt="75"alt="{item.image_name}" type="#_x0000_t75" style=“height:146.95pt;width:146.95pt;” filled=“f” o:preferrelative=“t” stroked=“f” coordsize=“21600,21600”><v:path/><v:fill on=“f” focussize=“0,0”/><v:stroke on=“f”/><v:imagedata src=“wordml://${item.index}.png” o:title=“微信图片_20200524140740”/><o:lock v:ext=“edit” aspectratio=“t”/><w10:wrap type=“none”/>w10:anchorlock/</v:shape></w:pict></#list><
要注意list的位置 ,然后将xml文件修改为ftl文件,直接改后缀名即可
java后台代码
@RequestMapping("/saveWenjuan")
public void saveWenjuan(HttpServletRequest request, HttpServletResponse response,@RequestParam MultipartFile[] myfiles) throws IOException{
Map<String,Object> dataMap = new HashMap<String, Object>();
try {
request.setCharacterEncoding("UTF-8");
dataMap.put("company", request.getParameter("company"));
System.out.println(request.getParameter("company"));
dataMap.put("department", request.getParameter("department"));
dataMap.put("persionname", request.getParameter("name"));
dataMap.put("phone", request.getParameter("phone"));
dataMap.put("email", request.getParameter("mail"));
dataMap.put("question", request.getParameter("question"));
dataMap.put("jianyi", request.getParameter("jianyi"));
dataMap.put("miaoshu", request.getParameter("miaoshu"));
BASE64Encoder base64Encoder =new BASE64Encoder();
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for (int i=0;i<myfiles.length;i++) {
if(myfiles[i]==null||myfiles[i].getSize()==0){
continue;
}
Map<String,Object> map = new HashMap<String, Object>();
String base64Encoderstr = base64Encoder.encode(myfiles[i].getBytes());
map.put("image_base64", base64Encoderstr);
map.put("image_name", myfiles[i].getName());
map.put("index", i);
list.add(map);
}
// System.out.println(base64Encoderstr);
dataMap.put("image",list);
//Configuration 用于读取ftl文件
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
/**
* 以下是两种指定ftl文件所在目录路径的方式,注意这两种方式都是
* 指定ftl文件所在目录的路径,而不是ftl文件的路径
*/
//指定路径的第一种方式(根据某个类的相对路径指定)
// configuration.setClassForTemplateLoading(this.getClass(), "");
//指定路径的第二种方式,我的路径是C:/a.ftl
String path = wenjuanController.class.getClassLoader().getResource("问卷模板3.ftl").getPath();
String realpath = path.substring(0, path.lastIndexOf("/"));
System.out.println(realpath);
configuration.setDirectoryForTemplateLoading(new File(realpath+"/"));
//输出文档路径及名称
Date day=new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
File outFile = new File(path.substring(0, path.indexOf("/", 2))+"//upload//"+request.getParameter("company"));
if(!outFile.exists()){
outFile.mkdirs();
}
File outFile2 = new File(path.substring(0, path.indexOf("/", 2))+"//upload//"+request.getParameter("company")+"//企业安全浏览器问卷"+df.format(day)+request.getParameter("name")+".doc");
//以utf-8的编码读取ftl文件
///wenjuan-web/src/main/resources/问卷模板.ftl
Template template = configuration.getTemplate("问卷模板3.ftl", "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile2), "utf-8"), 10240);
template.process(dataMap, out);
out.close();
response.setCharacterEncoding("GBK");
} catch (Exception e) {
e.printStackTrace();
}
唯一需要注意的一点就是要将上传过来的图片转换为base64编码,然后放入list中,代入word模板