使用freemarker生成word



1    word编辑好模板

1 普通字符串替换为${string}

2 表格循环用标签

<#list userList as user>

姓名:${user.userName}   性别:${user.sex}

</#list>

word模板原型如下图:

员工请假单

姓名

${docTempExp.name}

部门

${docTempExp.dept}

天数

${docTempExp.days}

请假类别

${docTempExp.leaveTypeString}

请假时间

${docTempExp.beginTime}

事由

${docTempExp.reason}

部门负责人审核

${docTempExp.checkUser1}

主管总监审核

${docTempExp.checkUser2}

主管副总审批

${docTempExp.checkUser3}

主管副总审批

${docTempExp.checkUser4}

流程说明:

1、普通员工请假二天以内的(含二天),请假单由部门负责人批准,人事备档;

2、二天以上,五天以内的(含五天),经部门负责人同意后,再由主管总监批准后人事备档;

3、五天以上的,经部门负责人、主管总监确认后,再由副总经理和总经理批准后人事备档;

4、部门负责人请事假三天以内的,请假单由主管总监批准;三天以上的,经主管副总确认后,由总经理批准后人事备档;

5、总监和副总请假,由总经理审批后,交由人事备档;

 

2    word模板另存为xml格式

3    xml模板文件后缀名改为.ftl

4    编辑ftl文件

1        编辑word模板时,${string}标签最好是手动一次性输入完毕,或者使用记事本统一将整个${string}编辑好之后,粘贴至word里边。

也就是说,不要在word里首先打完 ${ } 之后,又从其它地方把 string字符串粘贴至 { } 之间,这样在 word 转化为 xml时,解析会有问题,freemarker解析时,会报错。

2     处理   ${string}String的字段不能空,否则报错

Java代码

</pre><pre name="code" class="java" style="color: rgb(51, 51, 51); font-weight: bold;"><span style="font-size:14px;">/**
 * @Desc:word操作工具类
 * @Author:
 * @Date:2014/9/29
 */
public class WordUtil {
	private static Configuration configuration = null;
	
	static{
		//创建配置实例 
        configuration = new Configuration(); 
        //设置编码
        configuration.setDefaultEncoding("UTF-8");  
	}
	
	/**
	* @Desc:生成word文件
	* @param dataMap word中需要展示的动态数据,用map集合来保存
	* @param templateName word模板名称,例如:test.ftl
	* @param filePath 文件生成的目标路径,例如:D:/wordFile/
	* @param fileName 生成的文件名称,例如:test.doc
	*/
	public static File createWord(Map<?, ?> dataMap,String templateName){
		File outFile=null;    
		try {
	              
	            //ftl模板文件统一放至 com.lovo.oa.dm.template 包下面
	            configuration.setClassForTemplateLoading(WordUtil.class,"/com/lovo/oa/dm/template");
	            
	            //获取模板 
	            Template template = configuration.getTemplate(templateName+".ftl");          
	            //输出文件
	            String name = "temp" + (int) (Math.random() * 100000) + ".doc";
	            outFile =  new File(name);             
	            //将模板和数据模型合并生成文件 
	           // Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
	            Writer out = new OutputStreamWriter(new FileOutputStream(outFile),"utf-8");
	            //生成文件
	            template.process(dataMap, out); 
	            //关闭流
	            out.flush();
	            out.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return outFile;
	    }
	

}</span>

Web层控制器方法的编写

<span style="font-size:14px;">@RequestMapping("/downloadWord/{id}")
	public void downloadWord( @PathVariable int id, HttpServletResponse  resp){
		DocTempExp docTempExp=docTempExpService.getById(id);
		
		try {
			Class<?> clazz = docTempExp.getClass();
			Field[] fields=clazz.getDeclaredFields();
			for(int i=0, len=fields.length; i<len; i++){
				fields[i].setAccessible(true);
				Object obj = fields[i].get(docTempExp);
				if (obj == null) {
					obj = fields[i].getType().newInstance();
					fields[i].set(docTempExp, obj);
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} 
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("docTempExp", docTempExp);
		String fileName=docTempExp.getFilename();
		
		File f = WordUtil.createWord(map, fileName);
		try {
			InputStream fin = new FileInputStream(f);
			
			resp.setCharacterEncoding("utf-8");
			resp.setContentType("application/msword");
			resp.addHeader("Content-Disposition", "attachment;filename="+fileName+".doc");
			
			ServletOutputStream out = resp.getOutputStream();
			byte[] buffer = new byte[512];
			int bytesToRead = -1;
			while((bytesToRead = fin.read(buffer)) != -1) {
				out.write(buffer, 0, bytesToRead);
			}
			fin.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		f.delete();
	}</span>







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值