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

2 篇文章 0 订阅
2 篇文章 0 订阅
							## 2020上半年也已经过去,自己也从大三的学生走上实习的岗位,最近业务上需要导出word,自己也弄了两天,在这里记录一下自己的成长
  1. 制作模板
    首先你需要新建一个.docx文件,然后将需要替换的地方用${xxxxxx}代替,如下:
    在这里插入图片描述

  2. 完成填充之后将此文档的后缀改成.ftl
    像这样

  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("---------------------------");
	}

						导入项目
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬砖的阿陆

你的鼓励就是我前进的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值