Java - Jxls生成Excel报表

2017-06-06  本文已影响480人  33d31a1032df

Jxls是一个生成Excel的工具包。它采用Apache Jexl标签的方法,类似Jsp标签,写一个Excel模板,然后生成报表,非常灵活,简单。

先看一下Excel模板模板吧。

user.xlsx

接下来再看看Jxls是怎么使用这个模板文件吧。

public class JxlsTest {
    @Test
    public void test() throws Exception {
        List<User> users = listUser();
        try (InputStream input = new FileInputStream(getTemplate("user.xlsx"))) {
            try (OutputStream output = new FileOutputStream(getOutput("user.xlsx"))) {
                Context context = new Context();
                context.putVar("users", users);
                JxlsHelper.getInstance().processTemplate(input, output, context);
            }
        }
    }
    ...
}

最后我再介绍下Jxls是怎么自定义标签函数。

user-util.xls
public class JexlDateFunction {
    public static final String definition = "date";
    public String format(Date date, String pattern) {
        if (date == null)
            return null;
        if (pattern == null)
            pattern = "yyyy-MM-dd HH:mm:ss";
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(date);
    }
}
public class JxlsUtil {
    public static Boolean export(InputStream input, OutputStream output, Map<String, Object> data) {
        try {
            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            Transformer transformer = jxlsHelper.createTransformer(input, output);
            JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
            Map<String, Object> functions = new HashMap<>();
            functions.put(JexlDateFunction.definition, new JexlDateFunction());
            evaluator.getJexlEngine().setFunctions(functions);
            Context context = new Context();
            for (Map.Entry<String, Object> entry : data.entrySet())
                context.putVar(entry.getKey(), entry.getValue());
            jxlsHelper.processTemplate(context, transformer);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
public class JxlsUtilTest {
    @Test
    public void test() throws Exception {
        List<User> users = listUser();
        try (InputStream input = new FileInputStream(getTemplate("user-util.xlsx"))) {
            try (OutputStream output = new FileOutputStream(getOutput("user-util.xlsx"))) {
                Map<String, Object> data = new HashMap<>();
                data.put("users", users);
                JxlsUtil.export(input, output, data);
            }
        }
    }
    ...
}

完整示例:GitHub
PS:本文使用的是jxls-2.4.0

上一篇 下一篇

猜你喜欢

热点阅读