Search in sources :

Example 1 with AnalysisCell

use of com.alibaba.excel.write.metadata.fill.AnalysisCell in project easyexcel by alibaba.

the class ExcelWriteFillExecutor method doFill.

private void doFill(List<AnalysisCell> analysisCellList, Object oneRowData, FillConfig fillConfig, Integer relativeRowIndex) {
    if (CollectionUtils.isEmpty(analysisCellList) || oneRowData == null) {
        return;
    }
    Map dataMap;
    if (oneRowData instanceof Map) {
        dataMap = (Map) oneRowData;
    } else {
        dataMap = BeanMapUtils.create(oneRowData);
    }
    Set<String> dataKeySet = new HashSet<>(dataMap.keySet());
    RowWriteHandlerContext rowWriteHandlerContext = WriteHandlerUtils.createRowWriteHandlerContext(writeContext, null, relativeRowIndex, Boolean.FALSE);
    for (AnalysisCell analysisCell : analysisCellList) {
        CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(writeContext, null, analysisCell.getRowIndex(), null, analysisCell.getColumnIndex(), relativeRowIndex, Boolean.FALSE, ExcelContentProperty.EMPTY);
        if (analysisCell.getOnlyOneVariable()) {
            String variable = analysisCell.getVariableList().get(0);
            if (!dataKeySet.contains(variable)) {
                continue;
            }
            Object value = dataMap.get(variable);
            ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(dataMap, writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadClazz(), variable);
            cellWriteHandlerContext.setExcelContentProperty(excelContentProperty);
            createCell(analysisCell, fillConfig, cellWriteHandlerContext, rowWriteHandlerContext);
            cellWriteHandlerContext.setOriginalValue(value);
            cellWriteHandlerContext.setOriginalFieldClass(FieldUtils.getFieldClass(dataMap, variable, value));
            converterAndSet(cellWriteHandlerContext);
            WriteCellData<?> cellData = cellWriteHandlerContext.getFirstCellData();
            // Restyle
            if (fillConfig.getAutoStyle()) {
                Optional.ofNullable(collectionFieldStyleCache.get(currentUniqueDataFlag)).map(collectionFieldStyleMap -> collectionFieldStyleMap.get(analysisCell)).ifPresent(cellData::setOriginCellStyle);
            }
        } else {
            StringBuilder cellValueBuild = new StringBuilder();
            int index = 0;
            List<WriteCellData<?>> cellDataList = new ArrayList<>();
            cellWriteHandlerContext.setExcelContentProperty(ExcelContentProperty.EMPTY);
            cellWriteHandlerContext.setIgnoreFillStyle(Boolean.TRUE);
            createCell(analysisCell, fillConfig, cellWriteHandlerContext, rowWriteHandlerContext);
            Cell cell = cellWriteHandlerContext.getCell();
            for (String variable : analysisCell.getVariableList()) {
                cellValueBuild.append(analysisCell.getPrepareDataList().get(index++));
                if (!dataKeySet.contains(variable)) {
                    continue;
                }
                Object value = dataMap.get(variable);
                ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(dataMap, writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadClazz(), variable);
                cellWriteHandlerContext.setOriginalValue(value);
                cellWriteHandlerContext.setOriginalFieldClass(FieldUtils.getFieldClass(dataMap, variable, value));
                cellWriteHandlerContext.setExcelContentProperty(excelContentProperty);
                cellWriteHandlerContext.setTargetCellDataType(CellDataTypeEnum.STRING);
                WriteCellData<?> cellData = convert(cellWriteHandlerContext);
                cellDataList.add(cellData);
                CellDataTypeEnum type = cellData.getType();
                if (type != null) {
                    switch(type) {
                        case STRING:
                            cellValueBuild.append(cellData.getStringValue());
                            break;
                        case BOOLEAN:
                            cellValueBuild.append(cellData.getBooleanValue());
                            break;
                        case NUMBER:
                            cellValueBuild.append(cellData.getNumberValue());
                            break;
                        default:
                            break;
                    }
                }
            }
            cellValueBuild.append(analysisCell.getPrepareDataList().get(index));
            cell.setCellValue(cellValueBuild.toString());
            cellWriteHandlerContext.setCellDataList(cellDataList);
            if (CollectionUtils.isNotEmpty(cellDataList)) {
                cellWriteHandlerContext.setFirstCellData(cellDataList.get(0));
            }
            // Restyle
            if (fillConfig.getAutoStyle()) {
                Optional.ofNullable(collectionFieldStyleCache.get(currentUniqueDataFlag)).map(collectionFieldStyleMap -> collectionFieldStyleMap.get(analysisCell)).ifPresent(cell::setCellStyle);
            }
        }
        WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
    }
    // In the case of the fill line may be called many times
    if (rowWriteHandlerContext.getRow() != null) {
        WriteHandlerUtils.afterRowDispose(rowWriteHandlerContext);
    }
}
Also used : CellType(org.apache.poi.ss.usermodel.CellType) Setter(lombok.Setter) CellDataTypeEnum(com.alibaba.excel.enums.CellDataTypeEnum) Getter(lombok.Getter) BeanMapUtils(com.alibaba.excel.util.BeanMapUtils) ClassUtils(com.alibaba.excel.util.ClassUtils) HashMap(java.util.HashMap) WriteDirectionEnum(com.alibaba.excel.enums.WriteDirectionEnum) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) ExcelContentProperty(com.alibaba.excel.metadata.property.ExcelContentProperty) HashSet(java.util.HashSet) ListUtils(com.alibaba.excel.util.ListUtils) WriteCellData(com.alibaba.excel.metadata.data.WriteCellData) WriteTemplateAnalysisCellTypeEnum(com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum) AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell) StringUtils(com.alibaba.excel.util.StringUtils) Map(java.util.Map) Cell(org.apache.poi.ss.usermodel.Cell) FillWrapper(com.alibaba.excel.write.metadata.fill.FillWrapper) Sheet(org.apache.poi.ss.usermodel.Sheet) Iterator(java.util.Iterator) WriteHandlerUtils(com.alibaba.excel.util.WriteHandlerUtils) Collection(java.util.Collection) Set(java.util.Set) EqualsAndHashCode(lombok.EqualsAndHashCode) Objects(java.util.Objects) List(java.util.List) WriteContext(com.alibaba.excel.context.WriteContext) ExcelGenerateException(com.alibaba.excel.exception.ExcelGenerateException) FieldUtils(com.alibaba.excel.util.FieldUtils) MapUtils(com.alibaba.excel.util.MapUtils) RowWriteHandlerContext(com.alibaba.excel.write.handler.context.RowWriteHandlerContext) FillConfig(com.alibaba.excel.write.metadata.fill.FillConfig) CellWriteHandlerContext(com.alibaba.excel.write.handler.context.CellWriteHandlerContext) PoiUtils(org.apache.poi.hssf.usermodel.PoiUtils) Optional(java.util.Optional) Row(org.apache.poi.ss.usermodel.Row) AllArgsConstructor(lombok.AllArgsConstructor) CellStyle(org.apache.poi.ss.usermodel.CellStyle) WriteSheetHolder(com.alibaba.excel.write.metadata.holder.WriteSheetHolder) CellDataTypeEnum(com.alibaba.excel.enums.CellDataTypeEnum) CellWriteHandlerContext(com.alibaba.excel.write.handler.context.CellWriteHandlerContext) ArrayList(java.util.ArrayList) AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell) RowWriteHandlerContext(com.alibaba.excel.write.handler.context.RowWriteHandlerContext) WriteCellData(com.alibaba.excel.metadata.data.WriteCellData) ExcelContentProperty(com.alibaba.excel.metadata.property.ExcelContentProperty) HashMap(java.util.HashMap) Map(java.util.Map) AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell) Cell(org.apache.poi.ss.usermodel.Cell) HashSet(java.util.HashSet)

Example 2 with AnalysisCell

use of com.alibaba.excel.write.metadata.fill.AnalysisCell in project easyexcel by alibaba.

the class ExcelWriteFillExecutor method createCell.

private void createCell(AnalysisCell analysisCell, FillConfig fillConfig, CellWriteHandlerContext cellWriteHandlerContext, RowWriteHandlerContext rowWriteHandlerContext) {
    Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet();
    if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) {
        Row row = cachedSheet.getRow(analysisCell.getRowIndex());
        cellWriteHandlerContext.setRow(row);
        Cell cell = row.getCell(analysisCell.getColumnIndex());
        cellWriteHandlerContext.setCell(cell);
        rowWriteHandlerContext.setRow(row);
        rowWriteHandlerContext.setRowIndex(analysisCell.getRowIndex());
        return;
    }
    Sheet sheet = writeContext.writeSheetHolder().getSheet();
    Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.computeIfAbsent(currentUniqueDataFlag, key -> MapUtils.newHashMap());
    boolean isOriginalCell = false;
    Integer lastRowIndex;
    Integer lastColumnIndex;
    switch(fillConfig.getDirection()) {
        case VERTICAL:
            lastRowIndex = collectionLastIndexMap.get(analysisCell);
            if (lastRowIndex == null) {
                lastRowIndex = analysisCell.getRowIndex();
                collectionLastIndexMap.put(analysisCell, lastRowIndex);
                isOriginalCell = true;
            } else {
                collectionLastIndexMap.put(analysisCell, ++lastRowIndex);
            }
            lastColumnIndex = analysisCell.getColumnIndex();
            break;
        case HORIZONTAL:
            lastRowIndex = analysisCell.getRowIndex();
            lastColumnIndex = collectionLastIndexMap.get(analysisCell);
            if (lastColumnIndex == null) {
                lastColumnIndex = analysisCell.getColumnIndex();
                collectionLastIndexMap.put(analysisCell, lastColumnIndex);
                isOriginalCell = true;
            } else {
                collectionLastIndexMap.put(analysisCell, ++lastColumnIndex);
            }
            break;
        default:
            throw new ExcelGenerateException("The wrong direction.");
    }
    Row row = createRowIfNecessary(sheet, cachedSheet, lastRowIndex, fillConfig, analysisCell, isOriginalCell, rowWriteHandlerContext);
    cellWriteHandlerContext.setRow(row);
    cellWriteHandlerContext.setRowIndex(lastRowIndex);
    cellWriteHandlerContext.setColumnIndex(lastColumnIndex);
    Cell cell = createCellIfNecessary(row, lastColumnIndex, cellWriteHandlerContext);
    cellWriteHandlerContext.setCell(cell);
    if (isOriginalCell) {
        Map<AnalysisCell, CellStyle> collectionFieldStyleMap = collectionFieldStyleCache.computeIfAbsent(currentUniqueDataFlag, key -> MapUtils.newHashMap());
        collectionFieldStyleMap.put(analysisCell, cell.getCellStyle());
    }
}
Also used : AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell) Row(org.apache.poi.ss.usermodel.Row) CellStyle(org.apache.poi.ss.usermodel.CellStyle) Sheet(org.apache.poi.ss.usermodel.Sheet) AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell) Cell(org.apache.poi.ss.usermodel.Cell) ExcelGenerateException(com.alibaba.excel.exception.ExcelGenerateException)

Example 3 with AnalysisCell

use of com.alibaba.excel.write.metadata.fill.AnalysisCell in project easyexcel by alibaba.

the class ExcelWriteFillExecutor method prepareData.

/**
 * To prepare data
 *
 * @param cell          cell
 * @param rowIndex      row index
 * @param columnIndex   column index
 * @param firstRowCache first row cache
 * @return Returns the data that the cell needs to replace
 */
private String prepareData(Cell cell, int rowIndex, int columnIndex, Map<UniqueDataFlagKey, Set<Integer>> firstRowCache) {
    if (!CellType.STRING.equals(cell.getCellType())) {
        return null;
    }
    String value = cell.getStringCellValue();
    if (StringUtils.isEmpty(value)) {
        return null;
    }
    StringBuilder preparedData = new StringBuilder();
    AnalysisCell analysisCell = null;
    int startIndex = 0;
    int length = value.length();
    int lastPrepareDataIndex = 0;
    out: while (startIndex < length) {
        int prefixIndex = value.indexOf(FILL_PREFIX, startIndex);
        if (prefixIndex < 0) {
            break;
        }
        if (prefixIndex != 0) {
            char prefixPrefixChar = value.charAt(prefixIndex - 1);
            if (prefixPrefixChar == IGNORE_CHAR) {
                startIndex = prefixIndex + 1;
                continue;
            }
        }
        int suffixIndex = -1;
        while (suffixIndex == -1 && startIndex < length) {
            suffixIndex = value.indexOf(FILL_SUFFIX, startIndex + 1);
            if (suffixIndex < 0) {
                break out;
            }
            startIndex = suffixIndex + 1;
            char prefixSuffixChar = value.charAt(suffixIndex - 1);
            if (prefixSuffixChar == IGNORE_CHAR) {
                suffixIndex = -1;
            }
        }
        if (analysisCell == null) {
            analysisCell = initAnalysisCell(rowIndex, columnIndex);
        }
        String variable = value.substring(prefixIndex + 1, suffixIndex);
        if (StringUtils.isEmpty(variable)) {
            continue;
        }
        int collectPrefixIndex = variable.indexOf(COLLECTION_PREFIX);
        if (collectPrefixIndex > -1) {
            if (collectPrefixIndex != 0) {
                analysisCell.setPrefix(variable.substring(0, collectPrefixIndex));
            }
            variable = variable.substring(collectPrefixIndex + 1);
            if (StringUtils.isEmpty(variable)) {
                continue;
            }
            analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COLLECTION);
        }
        analysisCell.getVariableList().add(variable);
        if (lastPrepareDataIndex == prefixIndex) {
            analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
            // fix https://github.com/alibaba/easyexcel/issues/2035
            if (lastPrepareDataIndex != 0) {
                analysisCell.setOnlyOneVariable(Boolean.FALSE);
            }
        } else {
            String data = convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex));
            preparedData.append(data);
            analysisCell.getPrepareDataList().add(data);
            analysisCell.setOnlyOneVariable(Boolean.FALSE);
        }
        lastPrepareDataIndex = suffixIndex + 1;
    }
    // up successfully, so all data format to empty first.
    if (analysisCell != null && CollectionUtils.isNotEmpty(analysisCell.getVariableList())) {
        cell.setBlank();
    }
    return dealAnalysisCell(analysisCell, value, rowIndex, lastPrepareDataIndex, length, firstRowCache, preparedData);
}
Also used : AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell)

Example 4 with AnalysisCell

use of com.alibaba.excel.write.metadata.fill.AnalysisCell in project easyexcel by alibaba.

the class ExcelWriteFillExecutor method fill.

public void fill(Object data, FillConfig fillConfig) {
    if (data == null) {
        data = new HashMap<String, Object>(16);
    }
    if (fillConfig == null) {
        fillConfig = FillConfig.builder().build();
    }
    fillConfig.init();
    Object realData;
    // The data prefix that is populated this time
    String currentDataPrefix;
    if (data instanceof FillWrapper) {
        FillWrapper fillWrapper = (FillWrapper) data;
        currentDataPrefix = fillWrapper.getName();
        realData = fillWrapper.getCollectionData();
    } else {
        realData = data;
        currentDataPrefix = null;
    }
    currentUniqueDataFlag = uniqueDataFlag(writeContext.writeSheetHolder(), currentDataPrefix);
    // processing data
    if (realData instanceof Collection) {
        List<AnalysisCell> analysisCellList = readTemplateData(templateCollectionAnalysisCache);
        Collection<?> collectionData = (Collection<?>) realData;
        if (CollectionUtils.isEmpty(collectionData)) {
            return;
        }
        Iterator<?> iterator = collectionData.iterator();
        if (WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection()) && fillConfig.getForceNewRow()) {
            shiftRows(collectionData.size(), analysisCellList);
        }
        while (iterator.hasNext()) {
            doFill(analysisCellList, iterator.next(), fillConfig, getRelativeRowIndex());
        }
    } else {
        doFill(readTemplateData(templateAnalysisCache), realData, fillConfig, null);
    }
}
Also used : AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell) FillWrapper(com.alibaba.excel.write.metadata.fill.FillWrapper) Collection(java.util.Collection)

Example 5 with AnalysisCell

use of com.alibaba.excel.write.metadata.fill.AnalysisCell in project easyexcel by alibaba.

the class ExcelWriteFillExecutor method shiftRows.

private void shiftRows(int size, List<AnalysisCell> analysisCellList) {
    if (CollectionUtils.isEmpty(analysisCellList)) {
        return;
    }
    int maxRowIndex = 0;
    Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(currentUniqueDataFlag);
    for (AnalysisCell analysisCell : analysisCellList) {
        if (collectionLastIndexMap != null) {
            Integer lastRowIndex = collectionLastIndexMap.get(analysisCell);
            if (lastRowIndex != null) {
                if (lastRowIndex > maxRowIndex) {
                    maxRowIndex = lastRowIndex;
                }
                continue;
            }
        }
        if (analysisCell.getRowIndex() > maxRowIndex) {
            maxRowIndex = analysisCell.getRowIndex();
        }
    }
    Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet();
    int lastRowIndex = cachedSheet.getLastRowNum();
    if (maxRowIndex >= lastRowIndex) {
        return;
    }
    Sheet sheet = writeContext.writeSheetHolder().getCachedSheet();
    int number = size;
    if (collectionLastIndexMap == null) {
        number--;
    }
    if (number <= 0) {
        return;
    }
    sheet.shiftRows(maxRowIndex + 1, lastRowIndex, number, true, false);
    // The current data is greater than unity rowindex increase
    increaseRowIndex(templateAnalysisCache, number, maxRowIndex);
    increaseRowIndex(templateCollectionAnalysisCache, number, maxRowIndex);
}
Also used : AnalysisCell(com.alibaba.excel.write.metadata.fill.AnalysisCell) Sheet(org.apache.poi.ss.usermodel.Sheet)

Aggregations

AnalysisCell (com.alibaba.excel.write.metadata.fill.AnalysisCell)7 Sheet (org.apache.poi.ss.usermodel.Sheet)4 Cell (org.apache.poi.ss.usermodel.Cell)3 Row (org.apache.poi.ss.usermodel.Row)3 ExcelGenerateException (com.alibaba.excel.exception.ExcelGenerateException)2 FillWrapper (com.alibaba.excel.write.metadata.fill.FillWrapper)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 CellStyle (org.apache.poi.ss.usermodel.CellStyle)2 WriteContext (com.alibaba.excel.context.WriteContext)1 CellDataTypeEnum (com.alibaba.excel.enums.CellDataTypeEnum)1 WriteDirectionEnum (com.alibaba.excel.enums.WriteDirectionEnum)1 WriteTemplateAnalysisCellTypeEnum (com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum)1 WriteCellData (com.alibaba.excel.metadata.data.WriteCellData)1 ExcelContentProperty (com.alibaba.excel.metadata.property.ExcelContentProperty)1 BeanMapUtils (com.alibaba.excel.util.BeanMapUtils)1 ClassUtils (com.alibaba.excel.util.ClassUtils)1 FieldUtils (com.alibaba.excel.util.FieldUtils)1 ListUtils (com.alibaba.excel.util.ListUtils)1