首页 > 代码库 > velocity模板技术生成word文档

velocity模板技术生成word文档

本文介绍采用velocity技术在Java中生成word文档的方法。

1、新建一个word文档,编辑内容如下:


2、将上述word文档另存为htm格式的文件



3、新建一个Java Project项目velocityTest,加入Velocity所依赖的Jar包velocity-dep-1.5-beta2.jar。

4、在src目录下新建一个velocity.vm文件,将第二步生成的velocity.htm用文本编辑器打开,复制内容到velocity.vm中。内容如下:

<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 12">
<meta name=Originator content="Microsoft Word 12">
<link rel=File-List href=http://www.mamicode.com/"velocity.files/filelist.xml">>
5、新建一个VelocityUtil.java工具类,代码如下

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class VelocityUtil {

	public static void createDoc(VelocityContext vc, String templetePath) throws Exception {
		Properties ps = new Properties();
		ps.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "./src/");// 这是模板所在路径
		VelocityEngine ve = new VelocityEngine();
		ve.init(ps);
		ve.init();
		Template template = ve.getTemplate(templetePath, "utf-8");

		File srcFile = new File("E:/abc.doc");//输出路径
		FileOutputStream fos = new FileOutputStream(srcFile);
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
		template.merge(vc, writer);
		writer.flush();
		writer.close();
		fos.close();
	}

	public static void main(String[] args) {
		VelocityContext velocityContext = new VelocityContext();
		velocityContext.put("name", "张三");
		velocityContext.put("sex", "男");
		try {
			VelocityUtil.createDoc(velocityContext, "velocity.vm");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

6、运行即可,若出现乱码,则是velocity.vm中<meta http-equiv=Content-Type content="text/html; charset=gb2312">字符编码问题 改为

<meta http-equiv=Content-Type content="text/html; charset=utf-8">