读取指定单元格工具类

工具类

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.LinkedHashMap;

/**
 * @Author wpf
 * @Description 读取指定单元格工具类
 * @Date 2024/1/5
 */
public class ExcelReaderUtils {

    /**
     * @Author wpf
     * @Description 读取指定单元格
     * @Date 2024/1/5
     * @param filePath 文件路径
     * @param sheetName sheet名称
     * @param rowIndex 行号从0开始
     * @param colIndex 列号从0开始 如B3:(2,1)
     * @return String  内容
     */
    public static String readSpecificCell(String filePath, String sheetName, int rowIndex, int colIndex) {
        //获取监听器
        SpecificCellListener specificCellListener = new SpecificCellListener(rowIndex, colIndex);
        //读取数据
        EasyExcel.read(filePath, specificCellListener).sheet(sheetName).doRead();
        return specificCellListener.getSpecificCellValue();
    }

    /**
     * @Author wpf
     * @Description 内部监听器
     * @Date 2024/1/5
     */
    static class SpecificCellListener extends AnalysisEventListener<LinkedHashMap<Integer, String>> {

        //行号
        private int targetRowIndex;
        //列号
        private int targetColIndex;
        //值
        private String specificCellValue;

        public SpecificCellListener(int targetRowIndex, int targetColIndex) {
            this.targetRowIndex = targetRowIndex;
            this.targetColIndex = targetColIndex;
        }

        /**
         * @Author wpf
         * @Description 赋值指定单元格内容
         * @Date 2024/1/5
         */
        @Override
        public void invoke(LinkedHashMap<Integer, String> data, AnalysisContext context) {
            if (context.readRowHolder().getRowIndex() == targetRowIndex && data != null && targetColIndex < data.size()) {
                specificCellValue = data.get(targetColIndex).toString();
            }
        }

        /**
         * @Author wpf
         * @Description 处理完数据后的操作
         * @Date 2024/1/5
         */
        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
        }

        public String getSpecificCellValue() {
            return specificCellValue;
        }
    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值