欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于如何使用freemarker导出word(.doc)

程序员文章站 2022-07-15 10:18:48
...
							## 2020上半年也已经过去,自己也从大三的学生走上实习的岗位,最近业务上需要导出word,自己也弄了两天,在这里记录一下自己的成长
  1. 制作模板
    首先你需要新建一个.docx文件,然后将需要替换的地方用${xxxxxx}代替,如下:
    关于如何使用freemarker导出word(.doc)

  2. 完成填充之后将此文档的后缀改成.ftl
    关于如何使用freemarker导出word(.doc)

  3. 至此我们的word模板已经做好了,将他静静的躺在那里,待会我们会用到它。

  4. java代码中,将需要替换的内容以map的形式存进去

    	Map<String, Object> map = new HashMap<String, Object>();
    	//课程名称
    	map.put("kcmc","");
    		
    	map.put("kclx", "课程类型");
    		
    	//一级学科
    	
    		map.put("yjxk","一级学科");
    	
    	
    		map.put("ejxk", "二级学科");
    
  5. 利用模板输出新的doc

configuration.setClassForTemplateLoading(this.getClass(), "/template");  //此为代码中的相对路径
		Template t=null;
		try {
			//test.ftl为要装载的模板
			t = configuration.getTemplate("fctestpaper.ftl"); 
		} catch (IOException e) {
			e.printStackTrace();
		}
		//输出文档路径及名称
		File outFile = new File("E:/outFile.doc"); //想要输出的路径
		Writer out = null;
		FileOutputStream fos=null;
		try {
			fos = new FileOutputStream(outFile);
			OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
			//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
			//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
			 out = new BufferedWriter(oWriter); 
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		 
        try {
			t.process(map, out);  //重要
			out.close();
			fos.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        //System.out.println("---------------------------");
	}

						导入项目