关于jxls2.6.0后的版本使用的jexl3学习使用

访问jxls官网:http://jxls.sourceforge.net/

官网中也有例子:https://bitbucket.org/leonate/jxls-demo/src/master/。

按照官网中的顺序。第一个例子居然是自定义函数。而不是if each这样的命令。通过官网给出的例子。笔者这里进行了测试

package com.xkcoding.helloworld.util.jxls;


import org.apache.commons.compress.utils.Lists;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;


import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 *  jxls excel模版导出工具类
 *
 */
public class JxlsUtils {
    static {
        //添加自定义指令(可覆盖jxls原指令)
//        XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class);
//        XlsCommentAreaBuilder.addCommandMapping("comment", CommentCommand.class);
    }

    public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException {
        Context context = PoiTransformer.createInitialContext();
        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();
        // 设置静默模式,不报警告
        // evaluator.getJexlEngine().setSilent(true);
        // 函数强制,自定义功能
        Map<String, Object> functionMap = new HashMap<String, Object>();
        functionMap.put("utils", new JxlsUtils()); // 添加自定义功能
//        evaluator.getJexlEngine().setFunctions(funcs);//jexlEngine使用的setFunctions是jexl2中的方法
        JexlBuilder jb = new JexlBuilder();
        jb.namespaces(functionMap);
        JexlEngine je = jb.create();
        evaluator.setJexlEngine(je);

        // 必须要这个,否者表格函数统计会错乱
        jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
    }

    public static void exportExcel(File xls, File out, Map<String, Object> model)
            throws FileNotFoundException, IOException {
        exportExcel(new FileInputStream(xls), new FileOutputStream(out), model);
    }

    public static void exportExcel(String templatePath, OutputStream os, Map<String, Object> model) throws Exception {
        File template = getTemplate(templatePath);
        if (template != null) {
            exportExcel(new FileInputStream(template), os, model);
        } else {
            throw new Exception("Excel 模板未找到。");
        }
    }

    // 获取jxls模版文件
    public static File getTemplate(String path) {
        File template = new File(path);
        if (template.exists()) {
            return template;
        }
        return null;
    }

    // 日期格式化
    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;
    }

    public static ByteArrayOutputStream fileToBos(File file) throws IOException {
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int ch = 0;
        while ((ch = br.read()) != -1) {
            bos.write(ch);
        }
        return bos;
    }

    public static File getResource(String path) {
        if (path.contains("classpath")) {
            return new File(path.replace("classpath:", getClassPath()));
        }
        return new File(path);
    }

    public static String getClassPath() {
        return Thread.currentThread().getContextClassLoader().getResource("").getPath();
    }

    public static void main(String[] args) throws Exception {
//        String template = "classpath:template.xlsx";
        String output = "E:/事业部品牌推广费用(1).xlsx";
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("cc", "**事业部品牌部");
        map1.put("dd", "推广费用");
        map1.put("ee", "加盟推介会");
        map1.put("ff", 260000);
        map1.put("gg", 206701);
        map1.put("hh", 53000);
        map1.put("ii", 259701);

        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("cc", "**事业部品牌部");
        map2.put("dd", "推广费用");
        map2.put("ee", "旗舰店开业推广");
        map2.put("ff", 200000);
        map2.put("gg", "");
        map2.put("hh", 150000);
        map2.put("ii", 150000);

        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("cc", "**事业部品牌部");
        map3.put("dd", "推广费用");
        map3.put("ee", "**百店省推广");
        map3.put("ff", 200000);
        map3.put("gg", 70000);
        map3.put("hh", "");
        map3.put("ii", 70000);

        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("cc", "**事业部品牌部");
        map4.put("dd", "专业服务费");
        map4.put("ee", "**品牌策略");
        map4.put("ff", 400000);
        map4.put("gg", 400000);
        map4.put("hh", "");
        map4.put("ii", 400000);
        List<Map<String, Object>> data = Lists.newArrayList();
        data.add(map1);
        data.add(map2);
        data.add(map3);
        data.add(map4);

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("dataLs",data);
        model.put("title1","成本中心");
//        InputStream is = JxlsUtils.class.getResourceAsStream(template);
        InputStream is = new FileInputStream(JxlsUtils.getTemplate("C:/Users/85450/Desktop/aa.xlsx"));
        OutputStream os = new FileOutputStream(output);
        JxlsUtils.exportExcel(is, os, model);
        os.close();
    }
}

这里之前的evaluator.getJexlEngine().setFunctions(functionMap);是有问题的,从下载下来的例子中也可以看到此句话是被注释的。因为这里的jexlEngine使用的setFunctions是jexl2中的方法,而2.6.0后开始使用的是jexl3。我用的version是2.10.0

jexl3:        JexlBuilder jb = new JexlBuilder();
        jb.namespaces(functionMap);
        JexlEngine je = jb.create();
        evaluator.setJexlEngine(je);

需要将1位置的代码换为2中代码段 

maven依赖:

    <dependency>
      <groupId>org.jxls</groupId>
      <artifactId>jxls-poi</artifactId>
      <version>2.10.0</version>
    </dependency>

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jxls 是一个开源的 Java 库,用于导出 Excel 文件,它可以在 Java 中非常方便地进行使用。下面是使用 Jxls 导出 Excel 的步骤: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.jxls</groupId> <artifactId>jxls-core</artifactId> <version>1.0.15</version> </dependency> ``` 2. 准备 Excel 模板 在 Excel 文件中准备好要导出的内容,包括表头和数据部分。可以在表格中使用 ${} 来标记需要动态替换的数据。 3. 准备数据 在 Java 代码中准备好要导出的数据,可以使用 List 或者 Map 等类型来保存数据。 4. 创建模板引擎 使用 Jxls 提供的模板引擎创建一个模板,可以使用以下代码: ```java InputStream is = new FileInputStream(new File("template.xls")); Workbook workbook = WorkbookFactory.create(is); Transformer transformer = TransformerFactory.createTransformer(workbook, outputStream); ``` 其中,“template.xls”是你准备好的 Excel 模板文件名,outputStream 是导出文件的输出流。 5. 填充数据 使用 Jxls 提供的 API 填充数据,可以使用以下代码: ```java Map<String, Object> beans = new HashMap<>(); beans.put("dataList", dataList); transformer.transformXLS(new HashMap<>(), beans); ``` 其中,“dataList”是你准备好的数据,transformer.transformXLS() 方法将会把数据填充到模板中。 6. 输出文件 使用 Jxls 提供的 API 输出文件,可以使用以下代码: ```java transformer.flush(); outputStream.close(); ``` 这样就可以将 Excel 文件导出到 outputStream 中了。 以上是使用 Jxls 导出 Excel 的基本步骤,你可以根据自己的需求进行更多的调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值