word 导出编辑ftl_word导出(使用freemarker模板导出)

该代码示例展示了如何利用Freemarker模板引擎从Java应用动态创建文档。配置了模板目录,读取`.ftl`文件,将数据映射到模板并生成`.doc`文件。整个过程涉及文件路径设置、异常处理和文件写入操作。
摘要由CSDN通过智能技术生成

package com.shangyukeji.chuangke.controller;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.io.Writer;

import java.util.HashMap;

import java.util.Map;

import com.jfinal.plugin.activerecord.Db;

import com.jfinal.plugin.activerecord.Record;

import freemarker.template.Configuration;

import freemarker.template.DefaultObjectWrapper;

import freemarker.template.Template;

import freemarker.template.TemplateException;

import freemarker.template.TemplateExceptionHandler;

public class DocumentHandler {

private Configuration configuration = null;

private static String filepath = PropKit.use("config.properties").get("file.path");

public DocumentHandler() {

configuration = new Configuration();

configuration.setDefaultEncoding("utf-8");

}

public void createDoc(Map dataMap,String fileName) throws UnsupportedEncodingException {

Configuration configuration = new Configuration();

Template t=null;

try {

configuration.setDirectoryForTemplateLoading(new File("D:\\code"));

configuration.setDefaultEncoding("utf-8");

configuration.setObjectWrapper(new DefaultObjectWrapper());

configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

t = configuration.getTemplate("1-1.ftl");

} catch (IOException e) {

e.printStackTrace();

}

File outFile = new File(fileName);

Writer out = null;

FileOutputStream fos=null;

try {

fos = new FileOutputStream(outFile);

OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");

out = new BufferedWriter(oWriter);

} catch (FileNotFoundException e1) {

e1.printStackTrace();

}

try {

t.process(dataMap, out);

out.close();

fos.close();

} catch (TemplateException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void downloadWord(String id) throws UnsupportedEncodingException{

DocumentHandler mdoc = new DocumentHandler();

Map dataMap = new HashMap();

dataMap.put("aa", " ");

dataMap.put("bb", " ");

dataMap.put("cc", " ");

dataMap.put("dd", " ");

dataMap.put("ee", " ");

dataMap.put("ff", " ");

mdoc.createDoc(dataMap, "c:/合同协议.doc");

}

}

//模板**.xml或者**.ftl都应放在D:\\code文件夹下面(此文件可以随便定义,可以放置任何盘下),生成的文件'合同协议.doc'可以放置任何盘下,可以根据个人不同需要随意改动

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值