freemarker导出word文档
参考资料:
- http://blog.csdn.net/lun379292733/article/details/18673081
- http://www.tuicool.com/articles/J7rYVn6
实现过程
准备工作
1.新建word文档test.doc,需要替换的内容用${desc1}参数替换,其中参数部分最好从左到右手动输入,否则xml中会出现分割
2.word另存为word xml,重命名为test.xml
3.test.xml改为test.ftl
代码部分
1.工具类
static {
try{
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(WordGenerator.class, "/com/test/template/");
} catch (Exception e) {
log.error("初始化加载模板信息异常:\r\n" + e.getMessage(), e);
throw new RuntimeException(e);
}
}
public static File createWord(Map<String, Object> dataMap) {
File file = null;
Template t = null;
Writer w = null;
try {
file = new File("e:\\test\\test.doc");
//如果输出目标文件夹不存在,则创建
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
t = configuration.getTemplate("test.ftl");
w = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
//Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"UTF-8"));
t.process(dataMap, w);
w.close();
} catch (Exception e) {
log.error("生成word文件异常:\r\n" , e);
throw new RuntimeException(e);
} finally{
if(w != null)
try {
w.close();
} catch (IOException e) {
log.error("输出文件流关闭异常:\r\n", e);
}
}
return file;
}
2.调度类
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("desc1","test create word desc");
File file = createWord(dataMap);
String fileName = URLDecoder.decode(file.getName(),"utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
InputStream inputStream = null;
OutputStream os = null;
try {
File file = new File(path + realFileName);
inputStream = new FileInputStream(file);
response.addHeader("Content-Length", (new Long(file.length())).toString());
os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.flush();
} catch (Exception e) {
...
} finally {
...
}
3.前台调用
window.open(url);
##其他实现
表格循环
1.在word中增加一个表格样式
2.在xml中找到包含${listKey.title}等参数的行标签<w:tr w:rsidR="00986B72" ...>...</w:tr>
3.在行变迁外包裹
<#list userList as user> </#list>
标签,并在dataMap中增加名为userList的List元素4.其他与普通应用一致