Excel解析不规范数据报错解决方案

本文介绍了一种使用自定义工具类ExcelParseUtil来替代EasyExcel的方法,该工具类能够解析不规范的Excel数据,并进行数据校验和修正。通过提供File对象和目标实体类,即可读取并处理Excel文件中的内容,有效避免了EasyExcel可能出现的streamclosed异常。
摘要由CSDN通过智能技术生成

本文ExcelParseUtil替代EasyExcel解决easyexcel ioexception: stream closed问题

1.如图中excel(不规范excel数据)

2.使用ExcelParseUtil工具类解析Excel且校验并修正数据,最终读取数据

File file = new File("D:\\xx.xls");
List<QualifiedRateResult> qualifiedRateResults = ExcelParseUtil.parse(file, QualifiedRateResult.class);

3.ExcelParseUtil代码如下

import cn.hutool.core.date.DateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExcelParseUtil {

    public static Workbook workbook(File file) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(file);
        return Objects.requireNonNull(file.getName()).endsWith(".xlsx") ? new XSSFWorkbook(fileInputStream) :
                new HSSFWorkbook(fileInputStream);
    }

    public static <C> List<C> parse(File file, Class<C> clz) throws IOException, IllegalAccessException, InstantiationException {
        return parse(workbook(file), clz, 0, 1, null);
    }

    public static <C> List<C> parse(File file, Class<C> clz, int startRow) throws IOException, IllegalAccessException, InstantiationException {
        return parse(workbook(file), clz, 0, startRow, null);
    }

    public static <C> List<C> parse(File file, Class<C> clz, int sheetIndex, int startRow,
                                    ExcelParseListener<C> excelParseListener) throws IOException, IllegalAccessException, InstantiationException {
        return parse(workbook(file), clz, sheetIndex, startRow, excelParseListener);
    }

    public static <C> List<C> parse(Workbook workbook, Class<C> clz, int sheetIndex) throws IllegalAccessException, InstantiationException {
        return parse(workbook, clz, sheetIndex, 1, null);
    }

    public static <C> List<C> parse(Workbook workbook, Class<C> clz, int sheetIndex, int startRow,
                                    ExcelParseListener<C> excelParseListener) throws InstantiationException, IllegalAccessException {
        Sheet sheet = workbook.getSheetAt(sheetIndex);
        int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
        List<Field> fields = new ArrayList<>();
        Field[] declaredFields = clz.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            ExcelParseIgnore declaredAnnotation = field.getDeclaredAnnotation(ExcelParseIgnore.class);
            if (declaredAnnotation == null) {
                fields.add(field);
            }
        }
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setGroupingUsed(false);
        List<C> cResults = new ArrayList<>();
        for (int i = startRow; i < physicalNumberOfRows; i++) {
            Row row = sheet.getRow(i);
            C o = row2cResult(row, clz, fields,numberFormat);
            if (excelParseListener != null) {
                excelParseListener.invoke(o, row, fields);
            }
            cResults.add(o);
        }
        return cResults;
    }

    private static <C> C row2cResult(Row row, Class<C> clz, List<Field> classFields, NumberFormat numberFormat) throws IllegalAccessException, InstantiationException {
        Object instance = clz.newInstance();
        for (int i = 0; i < classFields.size(); i++) {
            Field field = classFields.get(i);
            String fieldType = field.getType().getName();
            Cell cell = row.getCell(i);
            switch (fieldType) {
                case "java.lang.String":
                    try {
                        ExcelParseDate annotation = field.getAnnotation(ExcelParseDate.class);
                        if (annotation == null) {
                            field.set(instance, stringCellValue(cell,numberFormat));
                        } else {
                            if (cell.getCellTypeEnum().name().equals("NUMERIC")) {
                                String format = DateUtil.format(cell.getDateCellValue(), "yyyy-MM-dd hh:mm:ss");
                                field.set(instance, format);
                            } else {
                                if (cell.getStringCellValue().length()>0){
                                    String date = DateUtil.parse(cell.getStringCellValue()).toString();
                                    field.set(instance, date);
                                }else {
                                    field.set(instance, LocalDate.now().atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
                                }
                            }
                        }
                    } catch (Exception e) {
                        field.set(instance, cell != null ? cell.toString() : null);
                    }
                    break;
                case "double":
                    try {
                        field.setDouble(instance, Double.parseDouble(numberCellValue(cell)));
                    } catch (Exception e) {
                        field.setDouble(instance, 0);
                    }
                    break;
                case "int":
                    try {
                        field.setInt(instance, Integer.parseInt(numberCellValue(cell).split("\\.")[0]));
                    } catch (Exception e) {
                        field.setInt(instance, 0);
                    }
                    break;
                case "long":
                    try {
                        field.setLong(instance, Long.parseLong(numberCellValue(cell).split("\\.")[0]));
                    } catch (Exception e) {
                        field.setLong(instance, 0);
                    }
                    break;
                case "float":
                    try {
                        field.setFloat(instance, Float.parseFloat(numberCellValue(cell)));
                    } catch (Exception e) {
                        field.setFloat(instance, 0);
                    }
                    break;
                case "java.lang.Double":
                    try {
                        field.set(instance,Double.parseDouble(numberCellValue(cell)));
                    } catch (Exception e) {
                        field.set(instance, 0);
                    }
                    break;
                case "java.lang.Integer":
                    try {
                        field.set(instance,Integer.parseInt(numberCellValue(cell).split("\\.")[0]));
                    } catch (Exception e) {
                        field.set(instance, 0);
                    }
                    break;
                case "java.lang.Long":
                    try {
                        field.set(instance,Long.parseLong(numberCellValue(cell).split("\\.")[0]));
                    } catch (Exception e) {
                        field.set(instance, 0);
                    }
                case "java.lang.Float":
                    try {
                        field.set(instance,Float.parseFloat(numberCellValue(cell)));
                    } catch (Exception e) {
                        field.set(instance, 0);
                    }
                    break;
                case "boolean":
                    try {
                        if (cell.getCellTypeEnum().name().equals("STRING")) {
                            field.setBoolean(instance, Boolean.parseBoolean(cell.getStringCellValue()));
                        } else {
                            field.setBoolean(instance, cell.getBooleanCellValue());
                        }
                    } catch (Exception e) {
                        field.setBoolean(instance, false);
                    }
                    break;
                case "java.lang.Boolean":
                    try {
                        if (cell.getCellTypeEnum().name().equals("STRING")) {
                            field.set(instance, Boolean.parseBoolean(cell.getStringCellValue()));
                        } else {
                            field.set(instance, cell.getBooleanCellValue());
                        }
                    } catch (Exception e) {
                        field.set(instance, false);
                    }
                    break;
                default:
                    field.set(instance, stringCellValue(cell,numberFormat));
                    break;
            }
        }
        return (C) instance;
    }

    public static String stringCellValue(Cell cell, NumberFormat numberFormat) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellTypeEnum().name()) {
            case "STRING":
                return cell.getStringCellValue();
            case "NUMERIC":
                return numberFormat.format(cell.getNumericCellValue());
            case "BOOLEAN":
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }

    private static String numberCellValue(Cell cell) {
        if (cell == null) {
            return "0";
        }
        switch (cell.getCellTypeEnum().name()) {
            case "NUMERIC":
                return String.valueOf(cell.getNumericCellValue());
            case "STRING":
                String stringNumber = stringNumber(cell.getStringCellValue());
                if (stringNumber.length() > 0){
                    if (stringNumber.contains(".")&&stringNumber.indexOf(".")!=stringNumber.lastIndexOf(".")){
                        return "0";
                    }else {
                        return stringNumber;
                    }
                }else {
                    return "0";
                }
            case "BOOLEAN":
                return cell.getBooleanCellValue()?"1":"0";
            default:
                return "0";
        }
    }

    public static String stringNumber(String str) {
        String regEx = "[^0-9.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

}
import org.apache.poi.ss.usermodel.Row;

import java.lang.reflect.Field;
import java.util.List;

public interface ExcelParseListener<C> {

    void invoke(C c, Row row, List<Field> fields);

}
package com.nod.excel.util;

import java.lang.annotation.*;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcelParseIgnore {
}
package com.nod.excel.util;

import java.lang.annotation.*;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcelParseDate {
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值