java freemark 使用_Java使用FreeMarker示例

public classExportMyWord {private Logger log = Logger.getLogger(ExportMyWord.class.toString());private Configuration config = null;publicExportMyWord() {

config= newConfiguration(Configuration.VERSION_2_3_28);

config.setDefaultEncoding("utf-8");

}/*** FreeMarker生成Word

*

*@paramdataMap 数据

*@paramtemplateName 目标名

*@paramsaveFilePath 保存文件路径的全路径名(路径+文件名)*/

public void createWord(Map dataMap, String templateName, String saveFilePath) throwsIOException {//加载模板(路径)数据//config.setClassForTemplateLoading(this.getClass(), "");//相对路径

String ftlPath = templateName.substring(0, templateName.lastIndexOf("/"));

config.setDirectoryForTemplateLoading(new File(ftlPath));//文件路径//设置异常处理器 这样的话 即使没有属性也不会出错 如:${list.name}...不会报错

config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

Template template= null;if (templateName.endsWith(".ftl")) {

templateName= templateName.substring(0, templateName.indexOf(".ftl"));

}try{

String ftlFile= templateName.substring(templateName.lastIndexOf("/")+1);

template= config.getTemplate(ftlFile + ".ftl");

}catch(TemplateNotFoundException e) {

log.error("模板文件未找到", e);

e.printStackTrace();

}catch(MalformedTemplateNameException e) {

log.error("模板类型不正确", e);

e.printStackTrace();

}catch(ParseException e) {

log.error("解析模板出错,请检查模板格式", e);

e.printStackTrace();

}catch(IOException e) {

log.error("IO读取失败", e);

e.printStackTrace();

}

File outFile= newFile(saveFilePath);if (!outFile.getParentFile().exists()) {

outFile.getParentFile().mkdirs();

}

Writer out= null;

FileOutputStream fos= null;try{

fos= newFileOutputStream(outFile);

}catch(FileNotFoundException e) {

log.error("输出文件时未找到文件", e);

e.printStackTrace();

}

out= new BufferedWriter(newOutputStreamWriter(fos));//将模板中的预先的代码替换为数据

try{

template.process(dataMap, out);

}catch(TemplateException e) {

log.error("填充模板时异常", e);

e.printStackTrace();

}catch(IOException e) {

log.error("IO读取时异常", e);

e.printStackTrace();

}

log.info("由模板文件:" + templateName + ".ftl" + " 生成文件 :" + saveFilePath + " 成功!!");try{

out.close();//web项目不可关闭

} catch(IOException e) {

log.error("关闭Write对象出错", e);

e.printStackTrace();

}

}/*** 获得图片的Base64编码

*

*@paramimgFile

*@return

*/

publicString getImageStr(String imgFile) {

InputStream in= null;byte[] data = null;try{

in= newFileInputStream(imgFile);

}catch(FileNotFoundException e) {

log.error("加载图片未找到", e);

e.printStackTrace();

}try{

data= new byte[in.available()];

in.read(data);//注:FileInputStream.available()方法可以从输入流中阻断由下一个方法调用这个输入流中读取的剩余字节数

in.close();

}catch(IOException e) {

log.error("IO操作图片错误", e);

e.printStackTrace();

}

BASE64Encoder encoder= newBASE64Encoder();returnencoder.encode(data);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值