使用freeMark生成word

本文详细介绍了如何利用Freemark模板引擎将数据转换为Word文档格式,并针对Word2003的兼容性问题提供了解决方案。包括模板创建、代码实现以及使用MyEclipse进行编辑的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前使用poi导出生成word发现使用word2003无法打开,下载兼容包也不行,poi对excel有较好的读写功能,但对于word则比较欠缺,2003和2007是不同的api,写存在很大的问题,后另找办法通过freemark生成word文档,那么什么是freemark?度娘说:FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。

那么如何使用它呢?首先我们用word2003生成大致的要导出的样式,然后将其另存为xml文档,修改后缀名为ftl文档,比如以下(下面表格中也写入你要的内容调整好样式,以便于在ftl文件中找到哪里是插入的内容):


当然你需要2003word能读写,那么得使用2003的去做他的模板,另存为mission.xml文件,改后缀为mission.ftl文件

将其放入比如src/com/ftl/下,用myeclipse打开,发现她的内容都写在一行了,相当的费劲,这时候我们需要freemark editor插件,摘选子别的博客: 首先在http://sourceforge.net/project/showfiles.php?group_id=163305下载插件,解压,将hudson.freemarker_ide_0.9.14文件夹放入eclipse下的plugins文件夹。

    发现hudson.freemarker_ide_0.9.14下的freemarker-2.3.6.jar包是比较早的版本,用新的freemarker-2.3.15.jar替换之,把MANIFEST.MF里的Bundle-ClassPath也改为freemarker-2.3.15.jar

    退出Eclipse再重启,在window --> Preferences 左边的树形栏里出现FreeMarker Editor一项新的内容。在General --> Editors --> File Associations下,为*.html和*.htm文件添加(add)FreeMarker Editor 作他们关联的编辑器(associated editors) , *.ftl文件的默认编辑器就是FreeMarker Editor。这样在编辑混合有HTML和FreeMarker标记的文件时,可以选择右击文件 --> Open with HTML Editor 或者 Open with FreeMarker Editor 

当然我们有可以使用jsp打开,按住ctrl +shift+F格式化一下,如果你的word文档有大量的样式,那么此时格式化后会有甚至上万行,此时myeclipse很可能会崩溃~~~~请尽量简单的做一个模板,



我这悲催的18000行前面大概都是样式,你会发现很对styles  fonts标签等等,正文当然是从<w:body>开始了,一般表格<w:tbl>开始其中<w:tr>表示一行<w:tc>表示一个单元格,<w:t>之间写内容,跟我们使用jsp一样,我们从都是便利一个集合去动态生成行以及填充内容的,freemark的遍历是<#list xxList as xx>其中xxList就相当于c:foreach中的items的值,xx相当于var  的值,其中内容写法也是和el一样${xx.userName},当然使用freemark的缺点就是如果某个属性为null则报错,那么我们可以用${xx.userName!""},使用感叹号判断如果为空,则显示后面的值,<#if flag ?? &&  flag!='N'>如果flag不为空 且不等于N   ... </#if>,如果某一个对象内部还有一个集合,则和cforeach一样的,<#list xx.yy as yy></#list>我们在动态生成tr的时候是在w:tr前加入list遍历,如果在一个单元格内遍历,则需要在<w:r>前去加入循环,ok

我们在action中怎么写呢?

	public String printDetail() throws UnsupportedEncodingException, FileNotFoundException{
		Map<String, Object> dataMap = new HashMap<String, Object>();
		MissionService service = new MissionServiceImpl();
		ExecuteService eService = new ExecuteServiceImpl();
		dbsMission = service.findById(Long.valueOf(id));
		dataMap.put("dbsMission", dbsMission);
		ScheduleService scheService = new ScheduleServiceImpl();
		if (dbsMission.getExeId() != null) {
			dbsExecute = eService.findById(dbsMission.getExeId());
			dataMap.put("dbsExecute", dbsExecute);
		}
		if(flag==null){
			flag="S";
		}
		if (!"N".equals(flag)) {// 承办人不看
			dbsSchedules = scheService.findByMission(dbsMission);
			dataMap.put("dbsSchedules", dbsSchedules);
		}
		dataMap.put("flag", flag);
		Random r = new Random();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
		StringBuffer sb = new StringBuffer();
		sb.append(sdf1.format(new Date()));
		sb.append("_");
		sb.append(r.nextInt(100));

		// 文件路径
		filePath = ServletActionContext.getServletContext().getRealPath("/") + "upload";

		// 文件唯一名称
		fileOnlyName = "事项详情_" + sb + ".doc";

		// 文件名称
		fileName = new String("事项详情.doc".getBytes(), "iso8859-1");
		/** 生成word */
		WordUtil.createWord(dataMap, "detail.ftl", filePath, fileOnlyName);
		downloadFile = new FileInputStream(filePath + File.separator + fileOnlyName);
		return SUCCESS;
	}

其中wordUtil中

    @SuppressWarnings("unchecked")
	public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
	        try {
	        //创建配置实例 
	        Configuration configuration = new Configuration();
	        
	        //设置编码
	            configuration.setDefaultEncoding("UTF-8");
	            
	            //ftl模板文件统一放至 com.lun.template 包下面
	            configuration.setClassForTemplateLoading(WordUtil.class,"/com/dbs/ftl/");
	            
	            //获取模板 
	            Template template = configuration.getTemplate(templateName);
	            
	            //输出文件
	            File outFile = new File(filePath+File.separator+fileName);
	            
	            //如果输出目标文件夹不存在,则创建
	            if (!outFile.getParentFile().exists()){
	                outFile.getParentFile().mkdirs();
	            }
	            
	            //将模板和数据模型合并生成文件 
	            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));


	            //生成文件
	            template.process(dataMap, out);
	            System.out.println("生成word ..");
	            //关闭流
	            out.flush();
	            out.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

OK,在struts2的配置文件中

 <action name="printDetail" class="com.dbs.action.MissionAction" method="printDetail">
	   <result name="success" type="stream">
	    <param name="contentDisposition">attachment;filename="${fileName}"</param>
	    <param name="inputName">downloadFile</param>
		<param name="bufferSize">4096</param>
		<param name="contentType">text/plain</param>
	   </result>
   <result name="error">/error.jsp</result>
  </action>

ok访问action就可以下载了 导出来


那么如何我


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值