用java将数据填充到ftl模板,导出word文档

准备ftl模板

先创建word文档,然后保存成ftl文件,找到需要填充的关键字,用KaTeX parse error: Expected 'EOF', got '#' at position 15: {key}替换,列表可得用<#̲list key as map…{map.key}。就相当于一个大Map里存有String和List这种结构数据。参考如下图:
在这里插入图片描述
在这里插入图片描述

工具类

package com.bj.aisino.afx.utils;

import com.aisino.aosplus.core.Constants;
import com.aisino.aosplus.core.util.Guid;
import com.bj.aisino.afx.declare.ReportAnalysis;
import com.sun.deploy.net.URLEncoder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.log4j.Logger;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

public class WordUtils {
	static Logger logger = Logger.getLogger(WordUtils.class);
	//配置信息,代码本身写的还是很可读的,就不过多注解了  
	private static Configuration configuration = null;  
	//这里注意的是利用WordUtils的类加载器动态获得模板文件的位置  
	private static final String templateFolder = WordUtils.class.getClassLoader().getResource("").getPath();  
	//private static final String templateFolder = "H:/我的项目/lm/lm/web/src/main/webapp/WEB-INF/templates";  
	static {  
//		configuration = new Configuration();  
		configuration = new Configuration(Configuration.VERSION_2_3_23);
		configuration.setDefaultEncoding("utf-8");  
		try {  
			configuration.setDirectoryForTemplateLoading(new File(templateFolder));  
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
	}  

	private WordUtils() {  
		throw new AssertionError();  
	}

	public static String exportMillCertificateWord(Map map, String title, String ftlFile) throws IOException {
		Template freemarkerTemplate = configuration.getTemplate(ftlFile);  
		File file = null;  
		InputStream fin = null;
		FileOutputStream out = null;
		String filePath = null;
		try {  
			// 调用工具类的createDoc方法生成Word文档  
			file = createDoc(map,freemarkerTemplate);  
			fin = new FileInputStream(file);  
			String fileName = title + Guid.g() + ".doc";
			filePath = Constants.WEBAPP_PATH +"/www/upload/" +fileName;
			File file2 = new File(filePath);
			if (!file2.exists()) {
				file2.createNewFile();
			}
			out = new FileOutputStream(file2);
			byte[] buffer = new byte[512];  // 缓冲区  
			int bytesToRead = -1;  
			// 通过循环将读入的Word文件的内容输出到指定文件中
			while((bytesToRead = fin.read(buffer)) != -1) {  
				out.write(buffer, 0, bytesToRead);  
			}  
		}catch (Exception e){
			logger.error("======文件生成失败,原因:{}",e);
		} finally {
			if(fin != null) fin.close();  
			if(out != null) out.close();  
			if(file != null) file.delete(); // 删除临时文件  
		}
		return filePath;
	}  

	private static File createDoc(Map<?, ?> dataMap, Template template) {  
		String name =  "sellPlan.doc";
		File f = new File(name);
		Template t = template;  
		try {  
			// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开  
			Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");  
			t.process(dataMap, w);  
			w.close();  
		} catch (Exception ex) {  
			ex.printStackTrace();  
			throw new RuntimeException(ex);  
		}  
		return f;  
	}

	public static void exportMillCertificateWordPro(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile) throws IOException {
		Template freemarkerTemplate = configuration.getTemplate(ftlFile);
		File file = null;
		InputStream fin = null;
		ServletOutputStream out = null;
		try {
			// 调用工具类的createDoc方法生成Word文档
			file = createDoc(map,freemarkerTemplate);
			fin = new FileInputStream(file);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/msword");
			// 设置浏览器以下载的方式处理该文件名
			String fileName = title + ".doc";
			response.setHeader("Content-Disposition", "attachment;filename="
					.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

			out = response.getOutputStream();
			byte[] buffer = new byte[512];  // 缓冲区
			int bytesToRead = -1;
			// 通过循环将读入的Word文件的内容输出到浏览器中
			while((bytesToRead = fin.read(buffer)) != -1) {
				out.write(buffer, 0, bytesToRead);
			}
		} finally {
			if(fin != null) fin.close();
			if(out != null) out.close();
			if(file != null) file.delete(); // 删除临时文件
		}
	}
}

我主要是用exportMillCertificateWord方法生成word文档,返回生成的word路径,因为我们封装了方法根据路径下载文件,做这个的时候主要是模板不会弄,工具类不就是拿来看看代码就能用了吗?所以我把模板制作放到了前面,希望对你有帮助。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在使用Java中的Freemarker模板导出Word文件时,默认情况下,文件的格式是由文件名后缀决定的。如果你想将其另存为doc格式而不是xml格式,你可以尝试以下方法: 1. 确保文件名的后缀为.doc或.docx。在保存文件时,将文件名设置为以.doc或.docx结尾,如"example.doc"或"example.docx"。 2. 确保使用的是正确的输出流。在保存文件时,确保你使用正确的输出流类型来保存Word文件。例如,使用FileOutputStream来保存文件。 以下是一个简单的示例代码,展示了如何使用Freemarker模板导出Word文件并将其另存为doc格式: ```java import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.*; public class WordExport { public static void main(String[] args) { Configuration configuration = new Configuration(Configuration.VERSION_2_3_31); configuration.setDefaultEncoding("UTF-8"); configuration.setClassForTemplateLoading(WordExport.class, "/templates"); try { Template template = configuration.getTemplate("template.ftl"); File outputFile = new File("output.doc"); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); template.process(dataModel, writer); writer.close(); } catch (IOException | TemplateException e) { e.printStackTrace(); } } } ``` 在上述代码中,我们将文件名设置为"output.doc",这样保存的就是doc格式的Word文件。 请确保你在代码中适当地替换模板路径、数据模型和文件名,以适应你的具体情况。 希望这能解决你的问题!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值