---
title: "freemaker生成word 和 excel"
author: "zcmor"
date: "2012-05-21T21:29:41Z"
tags: []
categories: ["编程语言"]
slug: "freemaker-word-excel"
draft: false
lastmod: "2012-05-21T21:30:16Z"
id: 1536940
url: "https://zcmor.iteye.com/blog/1536940"
---

最近正在用freemarker写一些小玩意儿，突然想到那么是不是可以用它来生成万恶的excel和world呢？在网上找了找，还真有人这么干过，而且干成功了。索性我也来试试。
   按照惯例还是来个helloworld吧。
    1）新建一个word，我用的是word 2010.在里面写个name。
    2）将它另存为world 2003 XML文档。
    3）将它拷贝到eclipse中，打开然后对他format一下，生成个好看点的格式。然后命名为testw.vm
    4）将刚才的name 替换为${name}。
    5) 用freemarker 处理该模板。源码如下：
		// 要填入模本的数据文件
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Configuration configuration = new Configuration();
		configuration.setDirectoryForTemplateLoading(new File("resources/"));
		configuration.setDefaultEncoding("UTF-8");//这里很重要
		dataMap.put("name", "goddy");
		dataMap.put("age", "11");
		Template t = null;
		try {
			// test.ftl为要装载的模板
			t = configuration.getTemplate("teste.vm");
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 输出文档路径及名称
		File outFile = new File("D:/outFile.doc");
		Writer out = null;
		out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
				outFile), "UTF-8"));//这里很重要

		t.process(dataMap, out);
     6）将源码贴到java过程中，将模板（testw.vm）拷贝到resources目录下（和src目录平级）。运行一把就可以看到在D盘看到outFile.doc文件了。打开一看，果然没有问题。如果出现该word文件打不开的情况就要注意，另存为的应该是2003版的xml，然后编码应该都是UTF-8，生成的应该是doc结尾的文档。
     7）生成excel和word一样，需要注意的就是选择2003版的xml，生成的文件为xls格式的文档，其他的和生成world的一样即可。
   按照这几个步骤就应该能生成基本的文档了，有了helloworld其他的应该都不是问题了~~~