通过freemarker生成word

通过freemarker将数据导出到word的模板中。

//新的接口,改为web页面填写生成word
	 @RequestMapping(value="/insertProcess.do")
     public @ResponseBody Object insertProcess(HttpServletRequest req ) {
		 String activityId = (String) req.getSession().getAttribute("activityId");
 		String processInfo = req.getParameter("insert");
 		String targetTable = req.getParameter("targetTable");
 		String basePath=servletContext.getRealPath("/").substring(0, servletContext.getRealPath("/").lastIndexOf("cn-admin"))+"/upload/cn-admin/process/";
 		String type = req.getParameter("type");
 		try {
 			req.setCharacterEncoding("UTF-8");
 		} catch (UnsupportedEncodingException e) {
 			e.printStackTrace();
 		}
 		
 		Freemarker freemark = new Freemarker("../template/");
//		freemark.setTemplateName("wordTemplate.ftl");
		freemark.setTemplateName("test.ftl");
		freemark.setFileName(new SimpleDateFormat("yyyy-MM-ddhh-mm-ss").format(new Date())+".doc");
		freemark.setFilePath(basePath);
		String fileName = freemark.createWord(processInfo,targetTable);
		String realUrl = "/upload/cn-admin/process/"+fileName;
		return 	processService.insert(processInfo,activityId,type,realUrl);
下面是freemarker类

package com.admin.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Freemarker {
	/**
	 * freemark初始化
	 * @param templatePath 模板文件位置
	 */
	public Freemarker(String templatePath) {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		configuration.setClassForTemplateLoading(this.getClass(),templatePath);		
	}	
	
	
	/**
	 * freemark模板配置
	 */
	private Configuration configuration;
	/**
	 * freemark模板的名字
	 */
	private String templateName;
	/**
	 * 生成文件名
	 */
	private String fileName;
	/**
	 * 生成文件路径
	 */
	private String filePath;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}

	public String createWord(String processInfo, String targetTable) {
		
		JSONObject json = JSONObject.fromObject(processInfo);
		targetTable = targetTable.substring(1);
		String[] temp  = targetTable.split("#");
		
	//	JSONArray target = JSONArray.fromObject(temp);
		
		Template t = null;
		try {
			t = configuration.getTemplate(templateName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		File outFile = new File(filePath+fileName);
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		Map map = new HashMap<String, Object>();
		
		map.put("forum", json.getString("name"));
	//	map.put("image", getImageStr());
		
		map.put("ForumTitle", json.getString("belong"));
		map.put("ParentOrganization", json.getString("parentorganization"));
		map.put("UndertakingOrganization", json.getString("undertakingorganization"));
		map.put("beginTime",json.getString("beginTime"));
		map.put("endTime",json.getString("endTime"));
		map.put("ForumLocation",json.getString("forumlocation"));
		map.put("ForumSize", json.getString("forumsize"));
		
		/*List<ProcessTable> ProcessTable = new ArrayList<ProcessTable>();
		String[] temp1 = null;
		
		
		for (int j = 0; j < temp.length; j++) {
				 temp1 = temp[j].split(",");
				 List<String> tmp = new ArrayList<String>();  
			        for(String str:temp1){  
			            if(str!=null && str.length()!=0){  
			                tmp.add(str);  
			            }  
			        }  
			ProcessTable pt = new ProcessTable();
			pt.setBeginDate(tmp.toArray(new String[0])[0]);
			pt.setEndDate(tmp.toArray(new String[0])[1]);
			pt.setSpeakTitle(tmp.toArray(new String[0])[2]);
			pt.setSpeakGuest(tmp.toArray(new String[0])[3]);
			pt.setGuestDes(tmp.toArray(new String[0])[4]);
			ProcessTable.add(pt);*/
		//}
		//map.put("table2", ProcessTable);
		try {
			t.process(map, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
}
模板的话先用word建好,如下图:

然后转成  ftl  格式,转好后要检查下标签名是否被错开了,错开的话要进行修补。

生成Word文件可以使用Apache POI库来操作,而使用Freemarker可以方便地生成Word模板。以下是Java通过Freemarker生成Word文件的代码实现: 1. 首先,需要引入Apache POI和Freemarker的相关依赖包。 2. 创建Freemarker配置对象,并设置模板文件路径和编码方式: ``` Configuration configuration = new Configuration(Configuration.VERSION_2_3_30); configuration.setDefaultEncoding("UTF-8"); configuration.setClassicCompatible(true); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setDirectoryForTemplateLoading(new File("templates")); ``` 其中,templates为存放模板文件的目录。 3. 加载模板文件,并生成数据模型: ``` Template template = configuration.getTemplate("template.ftl"); Map<String, Object> dataModel = new HashMap<>(); dataModel.put("title", "生成Word文件示例"); dataModel.put("content", "这是一份生成Word文件的示例文件。"); ``` 其中,template.ftl为模板文件名称,可以根据实际情况进行修改。dataModel是一个Map类型的数据结构,用于保存模板中需要替换的数据。 4. 创建Word文档对象,并读取模板内容: ``` XWPFDocument document = new XWPFDocument(); StringWriter writer = new StringWriter(); template.process(dataModel, writer); String content = writer.toString(); ``` 其中,XWPFDocument是Apache POI库中用于操作Word文档的类。 5. 将模板内容写入Word文档: ``` XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(content); ``` 6. 保存Word文档: ``` FileOutputStream out = new FileOutputStream("output.docx"); document.write(out); out.close(); document.close(); ``` 其中,output.docx为生成Word文件名称,可以根据实际情况进行修改。 完整代码示例: ``` import java.io.*; import java.util.*; import org.apache.poi.xwpf.usermodel.*; import freemarker.template.*; public class WordGenerator { public static void main(String[] args) throws Exception { Configuration configuration = new Configuration(Configuration.VERSION_2_3_30); configuration.setDefaultEncoding("UTF-8"); configuration.setClassicCompatible(true); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setDirectoryForTemplateLoading(new File("templates")); Template template = configuration.getTemplate("template.ftl"); Map<String, Object> dataModel = new HashMap<>(); dataModel.put("title", "生成Word文件示例"); dataModel.put("content", "这是一份生成Word文件的示例文件。"); XWPFDocument document = new XWPFDocument(); StringWriter writer = new StringWriter(); template.process(dataModel, writer); String content = writer.toString(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(content); FileOutputStream out = new FileOutputStream("output.docx"); document.write(out); out.close(); document.close(); } } ``` 其中,template.ftl文件内容如下: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>${title}</title> </head> <body> <h1>${title}</h1> <p>${content}</p> </body> </html> ``` 以上代码实现了通过Freemarker生成Word文件的功能,可以根据实际情况进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值