freemarker导出word文档

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.其他与普通应用一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值