调用方法
ExpTemplateTools tool = new ExpTemplateTools();
Map<String, Object> data = new HashMap<String, Object>();
try{
List list=this.suplogservice.downById(eventid);
data.put("bo", list);
}catch(Exception e){
data.put("error", 1);
data.put("msg", "查询失败");
e.printStackTrace();
}
String xml = "apply1.xml";
tool.createDoc(data, xml, "监理日志.zip",response,"监理日志");
模板写入方法。
public class ExpTemplateTools {private Configuration configuration = null;
public ExpTemplateTools() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
public void createDoc(Map map, String path, String cname, HttpServletResponse resp,String zname) throws Exception {
//获得模板路径
TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), "../templatestest/");
configuration.setTemplateLoader(templateLoader);
List list =(List) map.get("bo");
//获得模板对象
Template template = configuration.getTemplate(path, "UTF-8");
InputStream fin = null;
ServletOutputStream out = null;
ZipOutputStream zos=null;//压缩流对象
List finList=new ArrayList();//文件模板数据流对象集合
List titleList=new ArrayList();//文件模板数据流对象集合
try {
String displayname = new String(cname.getBytes("GBK"),"ISO-8859-1");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/msword");
// resp.setContentType("application/OCTET-STREAM");
resp.addHeader("Content-Disposition", "attachment;filename="+displayname);
for(int i=0;i<list.size();i++){
Map<String, Object> map1=new HashMap<String, Object>();
Map<String, Object> map2=(Map<String, Object>) list.get(i);
// String title=map2.get("noter")+"-"+map2.get("rq").toString().substring(0,10);
String title=map2.get("rq").toString().substring(0,10);
titleList.add(title);
map1.put("bo", list.get(i));//为模板赋值
map1.put("image", getImageStr("海管部项目负责人"));
map1.put("image1", getImageStr("EDIS部门负责人"));
// 输出文档路径及名称
File outFile = new File(""+i);
Writer writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
// 合并数据模型和模版,并将结果输出到out中
template.process(map1, writer);
fin = new FileInputStream(outFile);
finList.add(fin);
// 设置浏览器以下载的方式处理该文件,设置文件名称
// byte[] buffer = new byte[512]; // 缓冲区
// int bytesToRead = -1;
// // 通过循环将读入的Word文件的内容输出到浏览器中
// while ((bytesToRead = fin.read(buffer)) != -1) {
// out.write(buffer, 0, bytesToRead);
// }
//压缩
}
out = resp.getOutputStream();
zos = new ZipOutputStream(out);
for(int j=0;j<finList.size();j++){
zos.putNextEntry(new ZipEntry(zname+"-"+titleList.get(j)+".doc"));
byte[] bufferZip = new byte[1024];
int r = 0;
while ((r = ((FileInputStream) finList.get(j)).read(bufferZip)) != -1) {
zos.write(bufferZip, 0, r);
}
}
zos.flush();
zos.close();
} finally {
if (fin != null)
fin.close();
if (out != null)
out.close();
}
}
}