您的位置:首页 > 编程语言 > Java开发

freemarker用模板输出指定格式word文档

2016-08-11 14:35 393 查看

零基础步骤阅读。。。

1、创建一个word文档,以w为例

2、在w文档里输入(姓名:name),并另存为.xml格式

3、在firstobject XMLEditor(一款编辑xml的小软件)中打开x.xml文件

4、找到输入的name,在name加上&{}(freemarker的读取格式)即:${name}

5、创建一个项目,引进freemarker的jar包

6、将x.xml文件加载到项目中,并改格式为.ftl

7、创建ExportTemplateWord类

public class ExportTemplateWord {
public void exportWord() {
try {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("name", "zhangsan");//向dateMap中输入数据
Configuration configuration = new Configuration();
// 设置编码
configuration.setDefaultEncoding("UTF-8");
// 设置文件所在目录的路径
configuration.setDirectoryForTemplateLoading(new File(
"src/com/export/template"));//模板路径
// 获取模版
Template template = configuration.getTemplate("w.ftl");//模板文件
File outFile = new File("e:\\outword.doc");// 设置输出文件名,和保存路径
// 将模板和数据模型合并生成文件 重点设置编码集
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile), "UTF-8"));
// 生成文件
template.process(dataMap, out);
// 关闭流
out.flush();
out.close();
} catch (Exception e) {
throw new RuntimeException(e + "打印word");
}
}


8、创建一个测试类test,匿名实例ExportTemplateWord对象调用exportWord()方法

public class Test {

public static void main(String[] args) {
new ExportTemplateWord().exportWord();

}

}

9、现在已经生成word文档了,快去指定路径下查看吧

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java freemarker word 文档 xml