zoukankan      html  css  js  c++  java
  • java freemark生成word文档

    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("生成成功");
        }
    }
  • 相关阅读:
    SharePoint 2007中的Permission Level与Permission之间的关系
    如何确定一个SharePoint列表的ID?
    经典线程死锁
    SharePoint的Workflow History列表在哪里?
    SharePoint Designer中设计的workflow出错了, 怎么办?
    清除MOSS的Timer Job Cache的方法 Clear the SharePoint Configuration Cache
    sp_MSforeachtable和sp_MSforeachdb
    sa安全
    几个排名函数的区别
    递归限制
  • 原文地址:https://www.cnblogs.com/loveweiwei/p/4453298.html
Copyright © 2011-2022 走看看