首页 > 其他分享 >初始化获取Excel表头

初始化获取Excel表头

时间:2023-01-11 16:36:23浏览次数:45  
标签:初始化 Map Excel 表头 AnalysisContext context import public

工具类中获取title方法

 /*初始化获取表头*/
    public static List<String> getTitles(MultipartFile file) throws IOException{
        try(InputStream inputStream = file.getInputStream()){
            List<String> titles = new ArrayList<>(16);
            ExcelEventListener listener = new ExcelEventListener();
            EasyExcel.read(inputStream,listener).sheet(0).doReadSync();
            Map<Integer, String> map = listener.getMap().get(0);
            map.values().forEach(e->titles.add(e));
            return titles;
        }catch (Exception e){
            log.error("初始化获取表头失败!{}",e);
            throw e;
        }
    }

重写监听器

package indi.grant.financial.user.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Data
public class ExcelEventListener extends AnalysisEventListener<Map<Integer, String>> {

    private Map<Integer, Map<Integer, String>> map = new ConcurrentHashMap<>();

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("解析到一条头数据:{}, currentRowHolder", headMap.toString(),context.readRowHolder().getRowIndex());
        map.put(context.readRowHolder().getRowIndex(),headMap);
    }

    @Override
    public void invoke(Map<Integer, String> integerStringMap, AnalysisContext analysisContext) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("表头解析完成!");
    }
}

引入依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.6</version>
        </dependency>

 

标签:初始化,Map,Excel,表头,AnalysisContext,context,import,public
From: https://www.cnblogs.com/cgy-home/p/17044176.html

相关文章