一、集成
<dependency>
2 <groupId>org.apache.velocity</groupId>
3 <artifactId>velocity</artifactId>
4 <version>1.7</version>
5 </dependency>
6
7 <dependency>
8 <groupId>org.apache.velocity</groupId>
9 <artifactId>velocity-tools</artifactId>
10 <version>2.0</version>
11 </dependency>
二、简单使用
步骤:
先获取html generateHTML
将html存到工作空间 saveHtmlFile
生成excel文件 exportHtml encryptExcel
private void excel(String templatePath, String templateName, String outputName,
Map<String, Object> dataMap, String password) throws Exception {
String html = generateHTML(templatePath, templateName, dataMap);
saveHtmlFile(outputName, html);
logger.info("---------------begin->[{}]->[{}]->[{}]", templatePath, templateName, outputName + "------------------");
long s = System.currentTimeMillis();
new ExcelExporter().exportHtml(html, new File(getOutputPath() + outputName + ".xlsx"), false);
if (StringUtils.isNotBlank(password)) {
encryptExcel(getOutputPath() + outputName + ".xlsx", password);
}
logger.info("---------------end excel cost==={} ->[{}]->[{}]->[{}]", (System.currentTimeMillis()-s), templatePath, templateName, outputName + "------------------");
}
Template template = reportTemplateCacheService.getTemplate(templateName);
这里使用缓存来获取,nice,源码级设计
return TEMPLATE_CACHE.getIfPresent(templateName);
public String generateHTML(String templatePath, String templateName, Map<String, Object> map)
throws Exception {
Template template = null;
if (reportTemplateCacheService != null) {
template = reportTemplateCacheService.getTemplate(templateName);
}
if (template == null) {
logger.warn("generateHTML generate template do not hit the cache for template : {}",
templateName);
Properties props = new Properties();
props.put("resource.loader", "class");
props.put("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine velocityEngine = new VelocityEngine(props);
template = velocityEngine.getTemplate(templatePath + File.separator + templateName, "gbk");
}
VelocityContext context = new VelocityContext();
context.put("number", new NumberTool());
context.put("math", new MathTool());
context.put("date", new DateTool());
context.put("color", new NumberColorTool());
if (!CollectionUtils.isEmpty(map)) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
}
Writer writer = new StringWriter();
//template.merge(context, writer);
//从statement目录下加载report.vm模板
/* velocityEngine.mergeTemplate(templatePath + File.separator + templateName, "gbk", context, writer);*/
template.merge(context, writer);
return writer.toString();
}