主要的思路分为几步:
- 处理数据
- 将变量值填充到模板中
- 保存为文件
- 了解velocity语法
实现代码如下:
Content和MailHead都是实体类,contentTemplate是模板的名称
public void generateAttachment(String attachDir,String contentTemplate,String destFileName,
List<Content> contents,MailHead mailHead){
String localFilePath = attachDir+ File.separator + destFileName+".doc";
FileUtil.createFolderIfNotExists(attachDir);
VelocityEngine ve = initVelocityEngine();
VelocityContext context = new VelocityContext();
context.put("contents", contents);
context.put("metaInfo", mailHead) ;
// 生成附件文件的模板
String emailTemplate = contentTemplate + ".vm";
Template t = ve.getTemplate(emailTemplate);
StringWriter writer = new StringWriter();
t.merge(context, writer);
String attachContent = writer.toString();
FileUtil.saveAsFile(localFilePath, attachContent);
}
初始化VelocityEngine对象的代码如下:
private VelocityEngine initVelocityEngine() {
VelocityEngine ve = new VelocityEngine();
Properties prop = new Properties();
prop.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
prop.setProperty(Velocity.INPUT_ENCODING, "GBK");
prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
prop.setProperty("resource.loader", "class");
prop.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init(prop);
return ve;
}
将String类型的内容,保存为文件:
public static void saveAsFile(String file, String content) {
FileWriter fwriter = null;
try {
fwriter = new FileWriter(file);
fwriter.write(content);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fwriter.flush();
fwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}