Search in sources :

Example 1 with ReadCellData

use of com.alibaba.excel.metadata.data.ReadCellData in project diboot by dibo-software.

the class ReadExcelListener method onException.

/**
 * <h3>异常处理</h3>
 * 修补数据,回写错误
 */
@Override
public void onException(Exception exception, AnalysisContext context) throws Exception {
    // 数据类型转化异常
    if (exception instanceof ExcelDataConvertException) {
        ExcelDataConvertException dataConvertException = (ExcelDataConvertException) exception;
        Map<Integer, ReadCellData<?>> cellMap = new HashMap<>((Map) context.readRowHolder().getCellMap());
        Map<String, String> errorDataMap = new HashMap<>();
        Map<String, String> errorMsgMap = new HashMap<>();
        Consumer<ExcelDataConvertException> addErrorData = e -> {
            Integer columnIndex = e.getColumnIndex();
            String key = fieldNameMap.get(columnIndex);
            errorDataMap.put(key, cellMap.remove(columnIndex).getStringValue());
            errorMsgMap.put(key, "数据格式转换异常,非期望的数据类型[" + e.getExcelContentProperty().getField().getType().getSimpleName() + "]");
        };
        addErrorData.accept(dataConvertException);
        ReadListener<?> readListener = context.readWorkbookHolder().getReadListenerList().get(0);
        if (readListener instanceof ModelBuildEventListener) {
            while (true) {
                try {
                    ((ModelBuildEventListener) readListener).invoke(cellMap, context);
                    break;
                } catch (ExcelDataConvertException convertException) {
                    addErrorData.accept(convertException);
                }
            }
        } else {
            log.error("数据转换异常", exception);
            StringBuilder errorMsg = new StringBuilder().append("第 ").append(context.readRowHolder().getRowIndex() + 1).append(" 行,");
            errorMsgMap.forEach((fieldName, msg) -> errorMsg.append(fieldHeadMap.get(fieldName)).append(":").append(msg));
            addExceptionMsg(errorMsg.toString());
            return;
        }
        T currentRowAnalysisResult = (T) context.readRowHolder().getCurrentRowAnalysisResult();
        currentRowAnalysisResult.setRowIndex(context.readRowHolder().getRowIndex());
        errorDataMap.forEach(currentRowAnalysisResult::addInvalidValue);
        errorMsgMap.forEach(currentRowAnalysisResult::addComment);
        // 校验异常
        Set<ConstraintViolation<T>> constraintViolations = V.validateBean(currentRowAnalysisResult);
        if (V.notEmpty(constraintViolations)) {
            for (ConstraintViolation<T> violation : constraintViolations) {
                String propertyName = violation.getPropertyPath().toString();
                // 剔除解析识别的数据校验
                if (!errorDataMap.containsKey(propertyName)) {
                    currentRowAnalysisResult.addComment(propertyName, violation.getMessage());
                }
            }
        }
        this.cachedData(currentRowAnalysisResult);
    } else {
        log.error("出现未预知的异常:", exception);
        addExceptionMsg("第 " + (context.readRowHolder().getRowIndex() + 1) + " 行,解析异常: " + exception.getMessage());
    }
}
Also used : ExcelBindAnnoHandler(com.diboot.file.excel.cache.ExcelBindAnnoHandler) Setter(lombok.Setter) java.util(java.util) Getter(lombok.Getter) ExcelBindDict(com.diboot.file.excel.annotation.ExcelBindDict) EasyExcel(com.alibaba.excel.EasyExcel) ExcelDataConvertException(com.alibaba.excel.exception.ExcelDataConvertException) DuplicateStrategy(com.diboot.file.excel.annotation.DuplicateStrategy) WriteSheet(com.alibaba.excel.write.metadata.WriteSheet) BusinessException(com.diboot.core.exception.BusinessException) ExcelWriter(com.alibaba.excel.ExcelWriter) AnalysisContext(com.alibaba.excel.context.AnalysisContext) ReadListener(com.alibaba.excel.read.listener.ReadListener) ExcelHelper(com.diboot.file.util.ExcelHelper) Cons(com.diboot.file.config.Cons) Head(com.alibaba.excel.metadata.Head) BaseExcelModel(com.diboot.file.excel.BaseExcelModel) EmptyStrategy(com.diboot.file.excel.annotation.EmptyStrategy) ConstraintViolation(javax.validation.ConstraintViolation) BeanUtils(com.diboot.core.util.BeanUtils) BindDict(com.diboot.core.binding.annotation.BindDict) FileHelper(com.diboot.file.util.FileHelper) ExcelReadHeadProperty(com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty) ModelBuildEventListener(com.alibaba.excel.read.listener.ModelBuildEventListener) Status(com.diboot.core.vo.Status) NotNull(javax.validation.constraints.NotNull) Field(java.lang.reflect.Field) ReadCellData(com.alibaba.excel.metadata.data.ReadCellData) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) ExcelBindField(com.diboot.file.excel.annotation.ExcelBindField) Slf4j(lombok.extern.slf4j.Slf4j) BaseConfig(com.diboot.core.config.BaseConfig) S(com.diboot.core.util.S) V(com.diboot.core.util.V) Annotation(java.lang.annotation.Annotation) CommentWriteHandler(com.diboot.file.excel.write.CommentWriteHandler) ExcelDataConvertException(com.alibaba.excel.exception.ExcelDataConvertException) ReadCellData(com.alibaba.excel.metadata.data.ReadCellData) ModelBuildEventListener(com.alibaba.excel.read.listener.ModelBuildEventListener) ConstraintViolation(javax.validation.ConstraintViolation)

Example 2 with ReadCellData

use of com.alibaba.excel.metadata.data.ReadCellData in project easyexcel by alibaba.

the class RowTagHandler method endElement.

@Override
public void endElement(XlsxReadContext xlsxReadContext, String name) {
    XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
    RowTypeEnum rowType = MapUtils.isEmpty(xlsxReadSheetHolder.getCellMap()) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA;
    // It's possible that all of the cells in the row are empty
    if (rowType == RowTypeEnum.DATA) {
        boolean hasData = false;
        for (Cell cell : xlsxReadSheetHolder.getCellMap().values()) {
            if (!(cell instanceof ReadCellData)) {
                hasData = true;
                break;
            }
            ReadCellData<?> readCellData = (ReadCellData<?>) cell;
            if (readCellData.getType() != CellDataTypeEnum.EMPTY) {
                hasData = true;
                break;
            }
        }
        if (!hasData) {
            rowType = RowTypeEnum.EMPTY;
        }
    }
    xlsxReadContext.readRowHolder(new ReadRowHolder(xlsxReadSheetHolder.getRowIndex(), rowType, xlsxReadSheetHolder.getGlobalConfiguration(), xlsxReadSheetHolder.getCellMap()));
    xlsxReadContext.analysisEventProcessor().endRow(xlsxReadContext);
    xlsxReadSheetHolder.setColumnIndex(null);
    xlsxReadSheetHolder.setCellMap(new LinkedHashMap<>());
}
Also used : ReadCellData(com.alibaba.excel.metadata.data.ReadCellData) XlsxReadSheetHolder(com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder) ReadRowHolder(com.alibaba.excel.read.metadata.holder.ReadRowHolder) RowTypeEnum(com.alibaba.excel.enums.RowTypeEnum) Cell(com.alibaba.excel.metadata.Cell)

Example 3 with ReadCellData

use of com.alibaba.excel.metadata.data.ReadCellData in project easyexcel by alibaba.

the class ConverterUtils method convertToStringMap.

/**
 * Convert it into a String map
 *
 * @param cellDataMap
 * @param context
 * @return
 */
public static Map<Integer, String> convertToStringMap(Map<Integer, ReadCellData<?>> cellDataMap, AnalysisContext context) {
    Map<Integer, String> stringMap = MapUtils.newHashMapWithExpectedSize(cellDataMap.size());
    ReadSheetHolder readSheetHolder = context.readSheetHolder();
    int index = 0;
    for (Map.Entry<Integer, ReadCellData<?>> entry : cellDataMap.entrySet()) {
        Integer key = entry.getKey();
        ReadCellData<?> cellData = entry.getValue();
        while (index < key) {
            stringMap.put(index, null);
            index++;
        }
        index++;
        if (cellData.getType() == CellDataTypeEnum.EMPTY) {
            stringMap.put(key, null);
            continue;
        }
        Converter<?> converter = readSheetHolder.converterMap().get(ConverterKeyBuild.buildKey(String.class, cellData.getType()));
        if (converter == null) {
            throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null, "Converter not found, convert " + cellData.getType() + " to String");
        }
        try {
            stringMap.put(key, (String) (converter.convertToJavaData(new ReadConverterContext<>(cellData, null, context))));
        } catch (Exception e) {
            throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null, "Convert data " + cellData + " to String error ", e);
        }
    }
    return stringMap;
}
Also used : ExcelDataConvertException(com.alibaba.excel.exception.ExcelDataConvertException) ExcelDataConvertException(com.alibaba.excel.exception.ExcelDataConvertException) ReadCellData(com.alibaba.excel.metadata.data.ReadCellData) ReadSheetHolder(com.alibaba.excel.read.metadata.holder.ReadSheetHolder) ReadConverterContext(com.alibaba.excel.converters.ReadConverterContext) Map(java.util.Map)

Example 4 with ReadCellData

use of com.alibaba.excel.metadata.data.ReadCellData in project easyexcel by alibaba.

the class ModelBuildEventListener method buildUserModel.

private Object buildUserModel(Map<Integer, ReadCellData<?>> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) {
    ExcelReadHeadProperty excelReadHeadProperty = readSheetHolder.excelReadHeadProperty();
    Object resultModel;
    try {
        resultModel = excelReadHeadProperty.getHeadClazz().newInstance();
    } catch (Exception e) {
        throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), 0, new ReadCellData<>(CellDataTypeEnum.EMPTY), null, "Can not instance class: " + excelReadHeadProperty.getHeadClazz().getName(), e);
    }
    Map<Integer, Head> headMap = excelReadHeadProperty.getHeadMap();
    BeanMap dataMap = BeanMapUtils.create(resultModel);
    for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
        Integer index = entry.getKey();
        Head head = entry.getValue();
        String fieldName = head.getFieldName();
        if (!cellDataMap.containsKey(index)) {
            continue;
        }
        ReadCellData<?> cellData = cellDataMap.get(index);
        Object value = ConverterUtils.convertToJavaObject(cellData, head.getField(), ClassUtils.declaredExcelContentProperty(dataMap, readSheetHolder.excelReadHeadProperty().getHeadClazz(), fieldName), readSheetHolder.converterMap(), context, context.readRowHolder().getRowIndex(), index);
        if (value != null) {
            dataMap.put(fieldName, value);
        }
    }
    return resultModel;
}
Also used : Head(com.alibaba.excel.metadata.Head) ExcelDataConvertException(com.alibaba.excel.exception.ExcelDataConvertException) ExcelDataConvertException(com.alibaba.excel.exception.ExcelDataConvertException) ReadCellData(com.alibaba.excel.metadata.data.ReadCellData) BeanMap(org.springframework.cglib.beans.BeanMap) BeanMap(org.springframework.cglib.beans.BeanMap) Map(java.util.Map) ExcelReadHeadProperty(com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty)

Example 5 with ReadCellData

use of com.alibaba.excel.metadata.data.ReadCellData in project easyexcel by alibaba.

the class CsvExcelReadExecutor method dealRecord.

private void dealRecord(CSVRecord record, int rowIndex) {
    Map<Integer, Cell> cellMap = new LinkedHashMap<>();
    Iterator<String> cellIterator = record.iterator();
    int columnIndex = 0;
    Boolean autoTrim = csvReadContext.currentReadHolder().globalConfiguration().getAutoTrim();
    while (cellIterator.hasNext()) {
        String cellString = cellIterator.next();
        ReadCellData<String> readCellData = new ReadCellData<>();
        readCellData.setRowIndex(rowIndex);
        readCellData.setColumnIndex(columnIndex);
        // csv is an empty string of whether <code>,,</code> is read or <code>,"",</code>
        if (StringUtils.isNotBlank(cellString)) {
            readCellData.setType(CellDataTypeEnum.STRING);
            readCellData.setStringValue(autoTrim ? cellString.trim() : cellString);
        } else {
            readCellData.setType(CellDataTypeEnum.EMPTY);
        }
        cellMap.put(columnIndex++, readCellData);
    }
    RowTypeEnum rowType = MapUtils.isEmpty(cellMap) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA;
    ReadRowHolder readRowHolder = new ReadRowHolder(rowIndex, rowType, csvReadContext.readWorkbookHolder().getGlobalConfiguration(), cellMap);
    csvReadContext.readRowHolder(readRowHolder);
    csvReadContext.csvReadSheetHolder().setCellMap(cellMap);
    csvReadContext.csvReadSheetHolder().setRowIndex(rowIndex);
    csvReadContext.analysisEventProcessor().endRow(csvReadContext);
}
Also used : ReadCellData(com.alibaba.excel.metadata.data.ReadCellData) ReadRowHolder(com.alibaba.excel.read.metadata.holder.ReadRowHolder) RowTypeEnum(com.alibaba.excel.enums.RowTypeEnum) Cell(com.alibaba.excel.metadata.Cell) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

ReadCellData (com.alibaba.excel.metadata.data.ReadCellData)7 ExcelDataConvertException (com.alibaba.excel.exception.ExcelDataConvertException)3 Cell (com.alibaba.excel.metadata.Cell)3 ReadRowHolder (com.alibaba.excel.read.metadata.holder.ReadRowHolder)3 Map (java.util.Map)3 RowTypeEnum (com.alibaba.excel.enums.RowTypeEnum)2 Head (com.alibaba.excel.metadata.Head)2 ReadListener (com.alibaba.excel.read.listener.ReadListener)2 ExcelReadHeadProperty (com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty)2 EasyExcel (com.alibaba.excel.EasyExcel)1 ExcelWriter (com.alibaba.excel.ExcelWriter)1 AnalysisContext (com.alibaba.excel.context.AnalysisContext)1 ReadConverterContext (com.alibaba.excel.converters.ReadConverterContext)1 ExcelAnalysisException (com.alibaba.excel.exception.ExcelAnalysisException)1 ExcelAnalysisStopException (com.alibaba.excel.exception.ExcelAnalysisStopException)1 DataFormatData (com.alibaba.excel.metadata.data.DataFormatData)1 FormulaData (com.alibaba.excel.metadata.data.FormulaData)1 ModelBuildEventListener (com.alibaba.excel.read.listener.ModelBuildEventListener)1 ReadSheetHolder (com.alibaba.excel.read.metadata.holder.ReadSheetHolder)1 XlsxReadSheetHolder (com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder)1