曾经使用POI做过导出excel的功能,有次客户需要做导出word。使用过POI 导出excel都知道,
POI可以根据每行row提供第n个单元格cell操作的。但word 又不像excel 那样一格一格的那么整齐,
想把数据填到特定的地方还比较麻烦,所以,想到了Freemarker。
1.制作word的ftl模板
将word要填充数据的地方用***代替,然后另存为Word 2003 XML 文档(*.xml),保存的文件名不要是中文。
2.用Firstobject free XML editor打开xml文件,先格式化文件内容:选择Tools下的Indent【或者按快捷键F8】,
然后逐个ctrl+f 查找***,用freemarker的标识替换掉***,如:${name},这个name对应的是填充数据Map对应的key。
然后另存为.ftl文件,模板就做好啦!
3.代码实现:
导出word工具类:WordUtils
public class WordUtils {
private static Configuration configuration = null;
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
ResourceLoader resourceLoader = new DefaultResourceLoader();
//指定模板目录在类路径:WEB-INF/classes
Resource resource = resourceLoader.getResource("/");
File file = resource.getFile();
//设置要解析的模板所在的目录,并加载模板文件
configuration.setDirectoryForTemplateLoading(file);
///设置包装器,并将对象包装为数据模型
configuration.setObjectWrapper(new DefaultObjectWrapper());
} catch (IOException e) {
e.printStackTrace();
}
}
private WordUtils() {
throw new AssertionError();
}
/*
*导出单个word
*map:数据
*title:文件名
*ftlFile:模板文件
*/
public static void exportWord(Map map,String title,String ftlFile) {
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
HttpServletRequest request=WebUtils.getRequest();
HttpServletResponse response=WebUtils.getResponse();
try {
Template freemarkerTemplate = configuration.getTemplate(ftlFile,"UTF-8");
// 调用工具类的createDoc方法生成Word文档
String fileName = title+ ".doc";
file = createDoc(map,freemarkerTemplate,fileName);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区