在javaweb中使用freemarker生成word文档

Web项目中生成Word文档的方式有很多,基于Java的解决方案也是很多的,包括使用iText、jasperReport等各种方式,其实在从Office 2003开始,就可以将Office文档转换成XML文件,这样只要将需要填入的内容放上${}占位符,就可以使用像Freemarker这样的模板引擎将出现占位符的地方替换成真实数据,最后将文件保存成.ftl格式。


将这份word保存成xml格式,并修改将需要填入的内容放上${}占位符上,最后保存成table.ftl。

我们新建一个web工程,并添加freemarker的jar包,新建的项目的结构如图:


现在,我们介绍一些重要的类。

1.获取前台数据的控制层的类:

public class indexServlet extends HttpServlet {
	
	public indexServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		Type u=new Type();
		Map root = new HashMap();  
		//System.out.println(request.getParameter("cname"));
		//通过servlet获取前台数据
        root.put("cname", request.getParameter("cname"));
        root.put("cadd", request.getParameter("cadd"));

        File file = null;
				InputStream fin = null;
				ServletOutputStream out = null;
				try {
					//调用createDoc方法生成word文档
					file = WordGenerator.createDoc(root, "table");
					fin = new FileInputStream(file);
					
					response.setCharacterEncoding("utf-8");
					response.setContentType("application/msword");
					// 设置游览器以下载的方式处理该文件名为table.doc
					response.addHeader("Content-Disposition", "attachment;filename=table.doc");
					
					out = response.getOutputStream();
					byte[] buffer = new byte[512];
					int bytesToRead = -1;
					
					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();	// 
				}
				
				
				
		 

		
	}

}
2.对应前台页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
</head>

<body>
	<form name="loginform" method="post" action="indexServlet">
		<center>
		单位名称:<input name="cname" type="text"><br />
		作者姓名:<input name="cadd" type="text"><br /> 
		<input name="submit" type="submit"value="提交"> 
		<input name="reset" type="reset" value="重置">
		</center>
	</form>
</body>
</html>
3.web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <servlet-name>indexServlet</servlet-name>
    <servlet-class>com.servlet.indexServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>indexServlet</servlet-name>
    <url-pattern>/indexServlet</url-pattern>
  </servlet-mapping>
 
</web-app>

4. 工具类的代码:

public class WordGenerator {
	private static Configuration configuration = null;
	private static Map<String, Template> allTemplates = null;
	
	static {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		
		configuration.setClassForTemplateLoading(WordGenerator.class, "/com/templates");
		allTemplates = new HashMap<String, Template>();
		try {
			
			allTemplates.put("table", configuration.getTemplate("table.ftl"));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
/*
	private WordGenerator() {
		throw new AssertionError();
	}
*/
	public static File createDoc(Map<?, ?> dataMap, String type) {
		String name = "temp"  + ".doc";
		File f = new File(name);
		Template t = allTemplates.get(type);
		try {
			
			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;
	}

}

总结:

对于freemarker的包还需要多加熟悉,还有许多有待加深理解的地方。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值