jxls是一個簡單的、輕量級的excel導出庫,使用特定的標記在excel模板文件中來定義輸出格式和布局。java中成熟的excel導出工具有pol、jxl,但他們都是使用java代碼的方式來導出excel,編碼效率很低且不方便維護。
另外,jxls2.3的運行效率也相當不錯,經過測試,在禁用日志輸出的情況下,導出excel單表66535條記錄僅僅3000毫秒,與poi幾乎沒什么大的差距。
demo工程源碼下載:https://files.cnblogs.com/files/klguang/jxls-demo.zip
springboot-demo下載:https://files.cnblogs.com/files/klguang/jxls-springboot.zip
excel模板示例:
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 = "<AREA_LAST_CELL>")
這個標記定義了excel模板需要被解析的矩形區域為:A1到<AREA_LAST_CELL>。
XLS Command表示標記
XLS Command 使用excel注釋標注表示,命令格式如下:
jx:<command_name>(attr1='val1' attr2='val2' ... attrN='valN' lastCell=<last_cell> areas=["<command_area1>", "<command_area2", ... "<command_areaN>"])
<command_name> 是庫自帶的命名或是用戶自定義並注冊到XlsCommentAreaBuilder的命令。
each 命令是最常用的XLS命令,形如:
jx:each(items="employees" var="employee" lastCell="D4")
each 可以有如下一些屬性:
- items 上下文中集合的變量名;
- var 在遍歷集合的時候每一條記錄的變量名;
- area 該XLS Command的解析區域;
- direction 數據在excel中填充的方向,默認(DOWN)向下;
- select 其值為一個表達式,用來過濾數據。
jexl自定義工具函數
如果你需要自定jexl來處理數據,你可以從Transformer對象獲取JexlEngine引用,並對其配置。
下面的例子實現了將一個自定義jexl函數注冊到utils命名空間下:
JxlsHelper jxlsHelper = JxlsHelper.getInstance(); Transformer transformer = jxlsHelper.createTransformer(is, os); JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator)transformer.getTransformationConfig().getExpressionEvaluator(); Map<String, Object> funcs = new HashMap<String, Object>(); funcs.put("utils", new JxlsUtils()); //添加自定義功能 evaluator.getJexlEngine().setFunctions(funcs);
demo
工程目錄:
Employee.java
public class Employee { private String name; private Date birthDate; private BigDecimal payment; private BigDecimal bonus; // getter and setter }
建立excel模板:
工具類JxlsUtils.java
public class JxlsUtils { public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException { Context context = new Context(); if (model != null) { for (String key : model.keySet()) { context.putVar(key, model.get(key)); } } JxlsHelper jxlsHelper = JxlsHelper.getInstance(); Transformer transformer = jxlsHelper.createTransformer(is, os); JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig() .getExpressionEvaluator(); Map<String, Object> funcs = new HashMap<String, Object>(); funcs.put("utils", new JxlsUtils()); // 添加自定義功能 evaluator.getJexlEngine().setFunctions(funcs); jxlsHelper.processTemplate(context, transformer); } // 日期格式化 public String dateFmt(Date date, String fmt) { if (date == null) { return ""; } try { SimpleDateFormat dateFmt = new SimpleDateFormat(fmt); return dateFmt.format(date); } catch (Exception e) { e.printStackTrace(); } return ""; } // if判斷 public Object ifelse(boolean b, Object o1, Object o2) { return b ? o1 : o2; } }
入口ObjectCollectionDemo.java
public class ObjectCollectionDemoXlsx { static Logger logger = LoggerFactory.getLogger(ObjectCollectionDemoXlsx.class); public static void main(String[] args) throws ParseException, IOException { logger.info("Running Object Collection demo"); List employees = generateSampleEmployeeData(); OutputStream os = new FileOutputStream("target/object_collection_output.xlsx"); Map model=new HashMap(); model.put("employees", employees); model.put("nowdate", new Date()); InputStream inputStream = ObjectCollectionDemoXlsx.class.getClassLoader() .getResourceAsStream("jxls-template/object_collection_template.xlsx"); JxlsUtils.exportExcel(inputStream, os, model); os.close(); } public static List generateSampleEmployeeData() throws ParseException { List employees = new ArrayList(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd", Locale.US); employees.add( new Employee("Elsa", dateFormat.parse("1970-Jul-10"), 1500, 0.15) ); employees.add( new Employee("Oleg", dateFormat.parse("1973-Apr-30"), 2300, 0.25) ); employees.add( new Employee("Neil", dateFormat.parse("1975-Oct-05"), 2500, 0.00) ); employees.add( new Employee("Maria", dateFormat.parse("1978-Jan-07"), 1700, 0.15) ); employees.add( new Employee("John", dateFormat.parse("1969-May-30"), 2800, 0.20) ); return employees; } }
生成效果: