Velocity模板引擎實戰:動態生成HTML、Word、Excel等報表
阿新 • • 發佈:2019-02-20
先來一個工具類
package utils;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
/**
* 用於解析vm模版(world文件儲存為xml格式,然後把裡面的值改為velocity變數)
* 注意:解析excel的xml模版時
* 必須把<NumberFormat ss:Format="_ * #,##0_ ;_ * \-#,##0_ ;_ * "-"_ ;_ @_ "/> 刪掉
* 否則velocity處理模版後,匯出的xls會出現內容空白問題
* @author : <a href="mailto:[email protected]">李智龍</a>
* @date: 2018/3/28
*/
public class VelocityUtil {
private static VelocityEngine ve;
static {
ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class" , ClasspathResourceLoader.class.getName());
ve.init();
}
public static VelocityEngine getVe() {
return ve;
}
}
再來一個通用測試類
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import utils.VelocityUtil;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author: <a href="mailto:[email protected]">李智龍</a>
* @date: 2018/3/28
*/
public class HelloVelocity {
public static void main(String[] args) throws IOException {
VelocityEngine ve = VelocityUtil.getVe();
// 載入(獲取)模板物件
Template t = ve.getTemplate("wordTemp01.xml");
VelocityContext ctx = new VelocityContext();
// 域物件加入引數值
ctx.put("name", "李智龍");
ctx.put("age", "");
ctx.put("date", (new Date()).toString());
// list集合
List temp = new ArrayList();
temp.add("1");
temp.add("2");
ctx.put("list", temp);
File file = new File("export.doc");
StringWriter sw = new StringWriter();
t.merge(ctx, sw);
InputStream inputStream = new ByteArrayInputStream(sw.toString().getBytes("UTF-8"));
inputstreamtofile(inputStream, file);
System.out.println(sw.toString());
}
public static void inputstreamtofile(InputStream ins, File file){
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
一、HTML匯出
二、Word匯出
1、新建一個Word(wordTemp.doc),注意圈紅的部分
2、另存為xml檔案,使用瀏覽器開啟,注意上圖示紅的兩串程式碼位置不對
3、修改xml後的內容,對籃框內的整體進行迴圈
4、改完後再次開啟模板會發現,紅框中的內容隱藏了
5、替換通用測試類中的模板,執行程式碼
6、效果
三、Excel匯出
和world一樣儲存為xml格式,唯一的區別是,Excel需要把
<NumberFormat ss:Format="_ * #,##0_ ;_ * \-#,##0_ ;_ * "-"_ ;_ @_ "/>
這行幹掉(不止一行),否則匯出來的是空白