jxls根据模板导出Excel(二)

说明:本文是jxls根据模板导出Excel直接下载。

使用版本:jxls V2.10.0

excel模板版本:.xlsx格式

jxls官网地址:https://jxls.sourceforge.net/index.html

1、pom引用

 <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls-poi</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls-jexcel</artifactId>
            <version>1.0.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-jexl</artifactId>
            <version>2.1.1</version>
        </dependency>

  2、Controller调用方法

@PostMapping("/export")
    public AjaxResult export(HttpServletResponse response, Data data) throws IOException {
        String fileName = "test.xlsx";
        Map<String, Object> model  = dataService.getExportData(data,fileName);//拼接需要导出的内容
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        return JxlsUtils.exportExcelWithOS(response.getOutputStream(),fileName, model);
    }

  3、拼接数据

public Map<String, Object> getExportData(Data data,String fileName) {
        Map<String, Object> model = new HashMap<String, Object>(); // 绑定数据
        try {
            //可绑定单个参数,Excel模板中单元格直接用${test1}获取
            model.put("test1", "ttt");
			
            //可绑定list,使用${item.参数名}获取,需在列表首个单元格中增加批注
            List<Data1> taskItems = new ArrayList<Data1>();//Data1为某个数据类 
            for (int i=0;i<5;i++) {
			    Data1 d=new Data1;
				//d.setA("111");
                taskItems.add(d);
            }

            model.put("taskItems", taskItems);

        }catch (Exception ex){
            logger.error(ex.getMessage());
            System.out.println(ex.getMessage());
        }
        return model;
    }

  4、Excel导出方法

import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;


public class JxlsUtils {
    static{
       
    }

    /**
     * 根据模板生成文件,直接下载
     * @param os 流数据
     * @param templateFileName 模板文件名称
     * @param model 填充数据
     * @throws IOException
     */
    public static AjaxResult exportExcelWithOS(OutputStream os , String templateFileName, Map<String, Object> model) throws IOException{
        // 获取模板文件
        InputStream is = new FileInputStream(new File(模板文件路径地址 + templateFileName));
        try {
            // 输出
            Context context = PoiTransformer.createInitialContext();
            if (model != null) {
                for (String key : model.keySet()) {
                    context.putVar(key, model.get(key));
                }
            }
            JxlsHelper.getInstance().setUseFastFormulaProcessor(false).setEvaluateFormulas(true).processTemplate(is, os, context);
        }
        catch (Exception ex){
            System.out.println(ex.getMessage());
            logger.error(ex.getMessage());
            return AjaxResult.error(ex.getMessage());
        }finally {
            is.close();
        }
        return AjaxResult.success();
    }
}

  5、Excel模板,创建xlsx格式模板

添加批注,第一个单元格添加范围批注,jx:area(lastCell="K3")

list列表增加jx:each(items="taskItems" var="item" lastCell="K3")

 

之前写过另一种方法,先根据模板生成Excel,然后调用方法导出,可参考:https://www.cnblogs.com/webttt/p/14283481.html

 

热门相关:恭喜你被逮捕了   胸大的朋友姐姐们   妻子和妻子   比基尼酒吧:美味服务   法医娇宠,扑倒傲娇王爷