1.下载freemarker-2.3.19.jar

2.把要填充的内容用  ${title},${no}代替

3.用word 打开,保存为2003xml

4.打开生成xml文件,看下有没有把表达式  ${title},${no}   分开,如果分开了,那么要合并,最后保存为ftl文件

5.代码

public class DocUitlsDemo
{
    private Configuration configuration=null;
    public DocUitlsDemo(){
        configuration=new Configuration();
//        configuration.setClassicCompatible(false);//空值处理     
        configuration.setDefaultEncoding("UTF-8");
    }
    /**
     * 生成word
     * @param tmplatePath 模板的路径 /com/document/temlpate
     * @param templateName  "text.ftl"
     * @param data       map集合的数据
     * @param outputFile 文件输出路径
     * @throws Exception
     */
    public void createDoc(File tmplatePath,String templateName,Map<?,?> data,File outputFile) throws Exception {
        //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
        //这里我们的模板是放在com.havenliu.document.template包下面
        configuration.setDirectoryForTemplateLoading(tmplatePath);
        Template t=null;
        t = configuration.getTemplate(templateName);
        //输出文档路径及名称
        Writer out = null;
      //解决出现乱码
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile),"UTF-8"));
        t.process(data, out);
        out.close();
    }
    public static void main(String[] args)
    {
        Calendar calendar=Calendar.getInstance();
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH)+1;
        int day=calendar.get(Calendar.DAY_OF_MONTH);
        DocUitlsDemo demo=new DocUitlsDemo();
        
        Map<String , Object>data=new HashMap<String, Object>();
        data.put("no", "gk001");
        data.put("year", year+"");//这里的年份要用字符串来表示,不然的话,就当成数字了,会有 逗号的
        data.put("month", month);
        data.put("day", day);
        data.put("title", "2015-1-1");
        File tmplatePath=new File("d://");
        String tempalteName="template.ftl";
        File outputFile=new File(tmplatePath,"xx合同.doc");
        try
        {
            demo.createDoc(tmplatePath, tempalteName, data, outputFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        System.out.println("生成成功");
    }
}

 

posted on 2015-04-24 14:03  ccasdaaammm  阅读(405)  评论(0编辑  收藏  举报