Java中实现excel根据模板导出数据的方法有很多,一般简单的可以通过操作POI进行。还可以使用JXLS很轻松的实现模板导出。xls是一个简单的、轻量级的excel导出库,使用特定的标记在excel模板文件中来定义输出格式和布局。java中成熟的excel导出工具有pol、jxl,但他们都是使用java代码的方式来导出excel,编码效率很低且不方便维护。
一、pom文件
org.jxls
jxls
2.4.0
org.jxls
jxls-poi
1.0.11
org.jxls
jxls-jexcel
1.0.6
org.jxls
jxls-reader
2.0.0
二、模板文件的制作
Excel模板标记在jxls中的作用分为三部分:
bean属性标记
XLS Area定义标记
XLS Command表示标记
bean属性标记
jxls使用 Apache JEXL表达式语言来解析定义在excel模板中的表达式。JEXL与JSTL相似,并对JSTL进行了扩展。eg:
${department.chief.age} //属性可以是无限深度
${utils:dateFmt(date,”yyyy-MM-dd”)} //自定义工具函数
XLS Area定义标记
XLS Area 是JxlsPlus中的一个重要概念,它代表excel模板中需要被解析的矩形区域,由A1到最后一个单元格表示,有利于加快解析速度。
XLS Area 使用excel注释标注表示,它需要被定义在excel 模板的第一个单元格(A1):
jx:area(lastCell = "")
这个标记定义了excel模板需要被解析的矩形区域为:A1到。
XLS Command表示标记
XLS Command 使用excel注释标注表示,命令格式如下:
jx:(attr1='val1' attr2='val2' ... attrN='valN' lastCell= areas=["", "
... ""])
是库自带的命名或是用户自定义并注册到XlsCommentAreaBuilder的命令。
each 命令是最常用的XLS命令,形如:
jx:each(items="employees" var="employee" lastCell="D4")
each 可以有如下一些属性:
items 上下文中集合的变量名;
var 在遍历集合的时候每一条记录的变量名;
area 该XLS Command的解析区域;
direction 数据在excel中填充的方向,默认(DOWN)向下;
select 其值为一个表达式,用来过滤数据。
三、工具类JxlsUtils.java
public static void toPackageOs(HttpServletResponse response , String fileName)throws Exception{
response.setContentType("application/octet-stream;charset=utf-8");
String outFileName = fileName + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
response.setHeader("Content-Disposition", "attachment;filename=" + new String(outFileName.getBytes(),"iso-8859-1") + ".xls");
}
/**
* 生成模板输入流
* @param temPath
* @return
* @throws Exception
*/
public static InputStream toPackageIn(String temPath)throws Exception{
return new ClassPathResource((temPath)).getInputStream();
}
public static void exportExcel(List list, OutputStream os ,
InputStream in)throws Exception{
long exportExcelBegin = System.currentTimeMillis();
log.warn("exportExcel begin: " + exportExcelBegin);
Context context = new Context();
context.putVar("list", list);
JxlsHelper.getInstance().processTemplateAtCell(in, os, context, "Result!A1");
os.flush();
long exportExcelEnd = System.currentTimeMillis();
log.warn("exportExcel fininshed in: " + (exportExcelEnd - exportExcelBegin));
}
四、数据填充
private static String EXPORT_XLSX_CONFIG = "excel-templates/excel_substituteAffirm_info.xlsx";
private static String EXPORT_XLSX_FILENAME = "工程替换关系";
ServletOutputStream out = response.getOutputStream();
ExportUtil.toPackageOs(response, EXPORT_XLSX_FILENAME);
InputStream in = ExportUtil.toPackageIn(EXPORT_XLSX_CONFIG);
ExportUtil.exportExcel(resultList, out, in);
if (out != null) {
out.close();
in.close();
}