easypoi使用listener读取excel

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lang.zhou
 * @since 2023/10/8 14:28
 */
@EqualsAndHashCode(callSuper = true)
@Data
public abstract class AbstractExcelReadListener extends AnalysisEventListener {

    /**
     * 每次读取数量
     */
    protected int batchSize = 1000;
    protected int dataCount = 0;

    protected List dataList = new ArrayList<>();


    /**
     * 读取一行后回调
     * @param data  (列索引0开始 -> 值)
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        dataList.add(data);
        if(dataList.size() >= batchSize){
            dataCount += dataList.size();
            this.dataCallback(dataList);
            dataList.clear();
        }
    }

    /**
     * 读取结束回调
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(dataList.size() > 0){
            dataCount += dataList.size();
            this.dataCallback(dataList);
            dataList.clear();
        }
    }

    /**
     * 读取batchSize行后回调
     */
    public abstract void dataCallback(List dataList);

}
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;

import java.io.FileInputStream;
import java.util.List;
import java.util.Map;

/**
 * @author lang.zhou
 * @since 2023/10/8 14:26
 */
public class Test {

    public static void main(String[] args) throws Exception{
        FileInputStream stream = new FileInputStream("C:\\Users\\zhou\\Desktop\\1.xlsx");
        AbstractExcelReadListener> listener = new AbstractExcelReadListener>() {
            @Override
            public void dataCallback(List> dataList) {
                System.out.println();
            }
        };
        listener.setBatchSize(2);
        ExcelReader excelReader = EasyExcelFactory.read(stream, listener).headRowNumber(0).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        excelReader.finish();
    }

}

你可能感兴趣的:(poi,excel,poi)