使用freemarker导出word

来源:互联网 发布:软件的收费模式 编辑:程序博客网 时间:2024/05/29 10:43
     使用freemarker首先需要引入freemarker包。
在一些需要复杂样式的word导出时,代码操作将会变得非常麻烦或根本无法实现。freemarker导出word主要分为三个步骤:1.制作模板;2.填充数据;3.输出word;
一.制作模板
     首先编写word模板,记住图片的位置需要放一张图并设置好大小,然后将word文件保存为xml文件转换时应保存2003xml和勾选仅保存数据, 
下一步修改xml文件中标签,在需要循环的地方加上<#list cardList  as card> </#list>注 :cardlist 和card为自己命名数据的标识,需要输出使用${card.photo},在要输出图片的地方将base64替换为输出标签。例:
<w:pict><w:binData w:name="${"wordml://0200000"+card_index+2+".jpg"}"
xml:space="preserve">
${card.photo}
</w:binData><v:shape id="图片 1" o:spid="_x0000_i1025" type="#_x0000_t75"
style="width:80.25pt;height:99pt;visibility:visible;mso-wrap-style:square"><v:imagedata src="${"wordml://0200000"+card_index+2+".jpg"}" o:title="nophoto" /></v:shape></w:pict>
如果图片循环输出请修改图片的name和src不然输出将会是第一张图。修改完后将文件保存为ftl文件。模板制作完成
二。填充数据
try {
fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
OutputStream os = null;
Writer out = null;
Configuration configuration= null;
String templatePackagePath="/com/template";//模板包
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");//设置默认编码方式
configuration.setClassForTemplateLoading(this.getClass(),templatePackagePath);
Template t = null;
try {
t = configuration.getTemplate("***.ftl");模板
} catch (IOException e) {
e.printStackTrace();
}
Map<String, Object> dataMap = new HashMap<String, Object>();
List<Map<String, Object>> cardList1=new ArrayList<Map<String,Object>>();
for(int i=0;i<yxzg.length;i++)
{   Gy_cardDto dto=cardList.get(i);
Map<String, Object> map=new HashMap<String, Object>();
String photo=getImgString(***);//将图片转换为base64码
map.put("photo",photo);//填充数据
map.put("index", i+1);
cardList1.add(map);
}
dataMap.put("cardList", cardList1);
/**
*将图片转换为base64码
*/
 private String getImgString(String path)
{
String img=null;
InputStream in;
byte[] picdata=null;
try {
in=new FileInputStream(path);
picdata=new byte[in.available()];
in.read(picdata);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder=new BASE64Encoder();
img=encoder.encode(picdata);
return img;
}
三.输出文件
try{
os=getResponse().getOutputStream();
getResponse().reset();// 清空输出流
getResponse().setHeader("Content-disposition", "attachment; filename=" + fileName);// 设定输出文件头
out = new BufferedWriter(new OutputStreamWriter(os,"utf-8"));
}catch(Exception e)
{

}
try {
t.process(dataMap, out);
os.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}



0 0
原创粉丝点击