freemarker生成doc文档和生成docx文档

需要用到的jar包 链接:https://pan.baidu.com/s/1tTW0qJ2sjCZ881dUTXlBUA 密码:4oes

注意点:使用的文档模板为office word生成的,不要用wps

一.生成doc文档

1.生成xml文档模板,创建一个docx文件然后将后缀名改为zip(其实docx文档实际上是一个压缩文件,是可以解压出来的)

freemarker生成doc文档和生成docx文档

freemarker生成doc文档和生成docx文档

将document.xml解压出来,用notepad打开,语言选择xml(我也不知道为啥弄出来是一坨,改成xml还好看一点),可以在里面找到我们刚才的那三个参数,可以看到age缺少右括号,原因是被其他的代码冲散了将后面的那个括号剪切过来就好了

freemarker生成doc文档和生成docx文档

放到该目录下

freemarker生成doc文档和生成docx文档

前期准备工作好了,开始贴代码

1.把内容填充到xml


public  void createDoc(){
        //下面两个参数是调用report.ftl文件的
	    public  Configuration configuration = null;
	    private  Map<String, Template> allTemplates = null;
			configuration = new Configuration();
			configuration.setDefaultEncoding("utf-8");
			configuration.setClassForTemplateLoading(ReportService.class, "D://report");
			allTemplates = new HashMap<String,Template>();
			try {
				allTemplates.put("document", configuration.getTemplate("document.xml"));
			} catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace();
				throw new RuntimeException(e);
			}
			String name = "temp"+(int)(Math.random()*100000)+".doc";
			File f = new File(name);
			Template t  = allTemplates.get("document");
			//文件中替换的字段
			Map<String,String> dataMap = new HashMap<String, String>();
			dataMap.put("name", "张三");
			dataMap.put("sex", "男");
			dataMap.put("age", "老大不小了");
			Writer w;
			try {
				w = new OutputStreamWriter(new FileOutputStream(f),"utf-8");
				t.process(dataMap, w);
				w.close();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (TemplateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}