ExcelWriteFillExecutor.java 19.7 KB
Newer Older
庄家钜's avatar
庄家钜 已提交
1 2 3 4 5
package com.alibaba.excel.write.executor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
庄家钜's avatar
庄家钜 已提交
6
import java.util.HashSet;
庄家钜's avatar
庄家钜 已提交
7 8 9
import java.util.Iterator;
import java.util.List;
import java.util.Map;
庄家钜's avatar
庄家钜 已提交
10
import java.util.Set;
庄家钜's avatar
庄家钜 已提交
11 12 13

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
14
import org.apache.poi.ss.usermodel.CellType;
庄家钜's avatar
庄家钜 已提交
15 16 17 18
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import com.alibaba.excel.context.WriteContext;
19
import com.alibaba.excel.enums.CellDataTypeEnum;
庄家钜's avatar
庄家钜 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.util.WriteHandlerUtils;
import com.alibaba.excel.write.metadata.fill.AnalysisCell;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;

import net.sf.cglib.beans.BeanMap;

/**
 * Fill the data into excel
 *
 * @author Jiaju Zhuang
 */
public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor {

    private static final String ESCAPE_FILL_PREFIX = "\\\\\\{";
    private static final String ESCAPE_FILL_SUFFIX = "\\\\\\}";
    private static final String FILL_PREFIX = "{";
    private static final String FILL_SUFFIX = "}";
    private static final char IGNORE_CHAR = '\\';
    private static final String COLLECTION_PREFIX = ".";
    /**
     * Fields to replace in the template
     */
    private Map<Integer, List<AnalysisCell>> templateAnalysisCache = new HashMap<Integer, List<AnalysisCell>>(8);
    /**
     * Collection fields to replace in the template
     */
    private Map<Integer, List<AnalysisCell>> templateCollectionAnalysisCache =
        new HashMap<Integer, List<AnalysisCell>>(8);
    /**
     * Style cache for collection fields
     */
    private Map<Integer, Map<AnalysisCell, CellStyle>> collectionFieldStyleCache =
        new HashMap<Integer, Map<AnalysisCell, CellStyle>>(8);
庄家钜's avatar
庄家钜 已提交
62 63 64 65
    /**
     * Row height cache for collection
     */
    private Map<Integer, Short> collectionRowHeightCache = new HashMap<Integer, Short>(8);
庄家钜's avatar
庄家钜 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    /**
     * Last index cache for collection fields
     */
    private Map<Integer, Map<AnalysisCell, Integer>> collectionLastIndexCache =
        new HashMap<Integer, Map<AnalysisCell, Integer>>(8);

    public ExcelWriteFillExecutor(WriteContext writeContext) {
        super(writeContext);
    }

    public void fill(Object data, FillConfig fillConfig) {
        if (fillConfig == null) {
            fillConfig = FillConfig.builder().build(true);
        }
        fillConfig.init();
        if (data instanceof Collection) {
            List<AnalysisCell> analysisCellList = readTemplateData(templateCollectionAnalysisCache);
            Collection collectionData = (Collection)data;
            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);
            }
        } else {
            doFill(readTemplateData(templateAnalysisCache), data, fillConfig);
        }
    }

    private void shiftRows(int size, List<AnalysisCell> analysisCellList) {
        if (CollectionUtils.isEmpty(analysisCellList)) {
            return;
        }
        int maxRowIndex = 0;
        Integer sheetNo = writeContext.writeSheetHolder().getSheetNo();
        Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(sheetNo);
        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--;
        }
庄家钜's avatar
庄家钜 已提交
130
        sheet.shiftRows(maxRowIndex + 1, lastRowIndex, number, true, false);
庄家钜's avatar
庄家钜 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        for (AnalysisCell analysisCell : templateAnalysisCache.get(writeContext.writeSheetHolder().getSheetNo())) {
            if (analysisCell.getRowIndex() > maxRowIndex) {
                analysisCell.setRowIndex(analysisCell.getRowIndex() + number);
            }
        }
    }

    private void doFill(List<AnalysisCell> analysisCellList, Object oneRowData, FillConfig fillConfig) {
        Map dataMap;
        if (oneRowData instanceof Map) {
            dataMap = (Map)oneRowData;
        } else {
            dataMap = BeanMap.create(oneRowData);
        }
        WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder();
        Map<String, ExcelContentProperty> fieldNameContentPropertyMap =
            writeContext.currentWriteHolder().excelWriteHeadProperty().getFieldNameContentPropertyMap();
        for (AnalysisCell analysisCell : analysisCellList) {
            Cell cell = getOneCell(analysisCell, fillConfig);
            if (analysisCell.getOnlyOneVariable()) {
                String variable = analysisCell.getVariableList().get(0);
152 153 154
                if (writeContext.currentWriteHolder().ignore(variable, analysisCell.getColumnIndex())) {
                    continue;
                }
庄家钜's avatar
庄家钜 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167
                if (!dataMap.containsKey(variable)) {
                    continue;
                }
                Object value = dataMap.get(variable);
                CellData cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), cell,
                    value, fieldNameContentPropertyMap.get(variable));
                WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, null, Boolean.FALSE);
            } else {
                StringBuilder cellValueBuild = new StringBuilder();
                int index = 0;
                List<CellData> cellDataList = new ArrayList<CellData>();
                for (String variable : analysisCell.getVariableList()) {
                    cellValueBuild.append(analysisCell.getPrepareDataList().get(index++));
168 169 170
                    if (writeContext.currentWriteHolder().ignore(variable, analysisCell.getColumnIndex())) {
                        continue;
                    }
庄家钜's avatar
庄家钜 已提交
171 172 173 174 175 176 177
                    if (!dataMap.containsKey(variable)) {
                        continue;
                    }
                    Object value = dataMap.get(variable);
                    CellData cellData = convert(writeSheetHolder, value == null ? null : value.getClass(), cell, value,
                        fieldNameContentPropertyMap.get(variable));
                    cellDataList.add(cellData);
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
                    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;
                        }
庄家钜's avatar
庄家钜 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                    }
                }
                cellValueBuild.append(analysisCell.getPrepareDataList().get(index));
                cell.setCellValue(cellValueBuild.toString());
                WriteHandlerUtils.afterCellDispose(writeContext, cellDataList, cell, null, null, Boolean.FALSE);
            }
        }
    }

    private Cell getOneCell(AnalysisCell analysisCell, FillConfig fillConfig) {
        Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet();
        if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) {
            return cachedSheet.getRow(analysisCell.getRowIndex()).getCell(analysisCell.getColumnIndex());
        }
        Integer sheetNo = writeContext.writeSheetHolder().getSheetNo();
        Sheet sheet = writeContext.writeSheetHolder().getSheet();

        Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(sheetNo);
        if (collectionLastIndexMap == null) {
            collectionLastIndexMap = new HashMap<AnalysisCell, Integer>(16);
            collectionLastIndexCache.put(sheetNo, collectionLastIndexMap);
        }
        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 = sheet.getRow(lastRowIndex);
        if (row == null) {
            row = cachedSheet.getRow(lastRowIndex);
            if (row == null) {
                WriteHandlerUtils.beforeRowCreate(writeContext, lastRowIndex, null, Boolean.FALSE);
                if (fillConfig.getForceNewRow()) {
                    row = cachedSheet.createRow(lastRowIndex);
                } else {
                    row = sheet.createRow(lastRowIndex);
                }
庄家钜's avatar
庄家钜 已提交
254
                checkRowHeight(analysisCell, fillConfig, isOriginalCell, row, sheetNo);
庄家钜's avatar
庄家钜 已提交
255
                WriteHandlerUtils.afterRowCreate(writeContext, row, null, Boolean.FALSE);
庄家钜's avatar
庄家钜 已提交
256 257
            } else {
                checkRowHeight(analysisCell, fillConfig, isOriginalCell, row, sheetNo);
庄家钜's avatar
庄家钜 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
            }
        }
        Cell cell = row.getCell(lastColumnIndex);
        if (cell == null) {
            WriteHandlerUtils.beforeCellCreate(writeContext, row, null, lastColumnIndex, null, Boolean.FALSE);
            cell = row.createCell(lastColumnIndex);
            WriteHandlerUtils.afterCellCreate(writeContext, cell, null, null, Boolean.FALSE);
        }

        Map<AnalysisCell, CellStyle> collectionFieldStyleMap = collectionFieldStyleCache.get(sheetNo);
        if (collectionFieldStyleMap == null) {
            collectionFieldStyleMap = new HashMap<AnalysisCell, CellStyle>(16);
            collectionFieldStyleCache.put(sheetNo, collectionFieldStyleMap);
        }
        if (isOriginalCell) {
            collectionFieldStyleMap.put(analysisCell, cell.getCellStyle());
        } else {
            CellStyle cellStyle = collectionFieldStyleMap.get(analysisCell);
            if (cellStyle != null) {
                cell.setCellStyle(cellStyle);
            }
        }
        return cell;
    }

庄家钜's avatar
庄家钜 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    private void checkRowHeight(AnalysisCell analysisCell, FillConfig fillConfig, boolean isOriginalCell, Row row,
        Integer sheetNo) {
        if (!analysisCell.getFirstColumn() || !WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection())) {
            return;
        }
        if (isOriginalCell) {
            collectionRowHeightCache.put(sheetNo, row.getHeight());
            return;
        }
        Short rowHeight = collectionRowHeightCache.get(sheetNo);
        if (rowHeight != null) {
            row.setHeight(rowHeight);
        }
    }

庄家钜's avatar
庄家钜 已提交
298 299 300 301 302 303 304 305 306
    private List<AnalysisCell> readTemplateData(Map<Integer, List<AnalysisCell>> analysisCache) {
        Integer sheetNo = writeContext.writeSheetHolder().getSheetNo();
        List<AnalysisCell> analysisCellList = analysisCache.get(sheetNo);
        if (analysisCellList != null) {
            return analysisCellList;
        }
        Sheet sheet = writeContext.writeSheetHolder().getCachedSheet();
        analysisCellList = new ArrayList<AnalysisCell>();
        List<AnalysisCell> collectionAnalysisCellList = new ArrayList<AnalysisCell>();
庄家钜's avatar
庄家钜 已提交
307
        Set<Integer> firstColumnCache = new HashSet<Integer>();
庄家钜's avatar
庄家钜 已提交
308 309 310 311 312 313 314 315 316 317
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                if (cell == null) {
                    continue;
                }
庄家钜's avatar
庄家钜 已提交
318 319
                String preparedData =
                    prepareData(cell, analysisCellList, collectionAnalysisCellList, i, j, firstColumnCache);
庄家钜's avatar
庄家钜 已提交
320
                // Prevent empty data from not being replaced
321 322
                if (preparedData != null) {
                    cell.setCellValue(preparedData);
庄家钜's avatar
庄家钜 已提交
323
                }
庄家钜's avatar
庄家钜 已提交
324 325 326 327 328 329 330
            }
        }
        templateAnalysisCache.put(sheetNo, analysisCellList);
        templateCollectionAnalysisCache.put(sheetNo, collectionAnalysisCellList);
        return analysisCache.get(sheetNo);
    }

庄家钜's avatar
庄家钜 已提交
331
    /**
庄家钜's avatar
庄家钜 已提交
332
     * To prepare data
庄家钜's avatar
庄家钜 已提交
333
     *
334
     * @param cell
庄家钜's avatar
庄家钜 已提交
335 336 337 338
     * @param analysisCellList
     * @param collectionAnalysisCellList
     * @param rowIndex
     * @param columnIndex
庄家钜's avatar
庄家钜 已提交
339
     * @param firstColumnCache
340
     * @return Returns the data that the cell needs to replace
庄家钜's avatar
庄家钜 已提交
341
     */
342
    private String prepareData(Cell cell, List<AnalysisCell> analysisCellList,
庄家钜's avatar
庄家钜 已提交
343
        List<AnalysisCell> collectionAnalysisCellList, int rowIndex, int columnIndex, Set<Integer> firstColumnCache) {
344 345 346 347
        if (!CellType.STRING.equals(cell.getCellTypeEnum())) {
            return null;
        }
        String value = cell.getStringCellValue();
庄家钜's avatar
庄家钜 已提交
348
        if (StringUtils.isEmpty(value)) {
349
            return null;
庄家钜's avatar
庄家钜 已提交
350
        }
351
        StringBuilder preparedData = new StringBuilder();
庄家钜's avatar
庄家钜 已提交
352
        AnalysisCell analysisCell = null;
庄家钜's avatar
庄家钜 已提交
353

庄家钜's avatar
庄家钜 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
        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 out;
            }
            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) {
庄家钜's avatar
庄家钜 已提交
383
                analysisCell = initAnalysisCell(rowIndex, columnIndex);
庄家钜's avatar
庄家钜 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
            }
            String variable = value.substring(prefixIndex + 1, suffixIndex);
            if (StringUtils.isEmpty(variable)) {
                continue;
            }
            if (variable.startsWith(COLLECTION_PREFIX)) {
                variable = variable.substring(1);
                if (StringUtils.isEmpty(variable)) {
                    continue;
                }
                analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COLLECTION);
            }
            analysisCell.getVariableList().add(variable);
            if (lastPrepareDataIndex == prefixIndex) {
                analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
            } else {
400 401 402
                String data = convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex));
                preparedData.append(data);
                analysisCell.getPrepareDataList().add(data);
庄家钜's avatar
庄家钜 已提交
403 404 405 406
                analysisCell.setOnlyOneVariable(Boolean.FALSE);
            }
            lastPrepareDataIndex = suffixIndex + 1;
        }
庄家钜's avatar
庄家钜 已提交
407 408 409 410 411 412 413
        return dealAnalysisCell(analysisCell, value, rowIndex, lastPrepareDataIndex, length, analysisCellList,
            collectionAnalysisCellList, firstColumnCache, preparedData);
    }

    private String dealAnalysisCell(AnalysisCell analysisCell, String value, int rowIndex, int lastPrepareDataIndex,
        int length, List<AnalysisCell> analysisCellList, List<AnalysisCell> collectionAnalysisCellList,
        Set<Integer> firstColumnCache, StringBuilder preparedData) {
庄家钜's avatar
庄家钜 已提交
414 415 416 417 418 419 420 421 422 423
        if (analysisCell != null) {
            if (lastPrepareDataIndex == length) {
                analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
            } else {
                analysisCell.getPrepareDataList().add(convertPrepareData(value.substring(lastPrepareDataIndex)));
                analysisCell.setOnlyOneVariable(Boolean.FALSE);
            }
            if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) {
                analysisCellList.add(analysisCell);
            } else {
庄家钜's avatar
庄家钜 已提交
424 425 426 427
                if (!firstColumnCache.contains(rowIndex)) {
                    analysisCell.setFirstColumn(Boolean.TRUE);
                    firstColumnCache.add(rowIndex);
                }
庄家钜's avatar
庄家钜 已提交
428 429
                collectionAnalysisCellList.add(analysisCell);
            }
430
            return preparedData.toString();
庄家钜's avatar
庄家钜 已提交
431
        }
432
        return null;
庄家钜's avatar
庄家钜 已提交
433 434
    }

庄家钜's avatar
庄家钜 已提交
435 436 437 438 439 440 441 442 443 444
    private AnalysisCell initAnalysisCell(Integer rowIndex, Integer columnIndex) {
        AnalysisCell analysisCell = new AnalysisCell();
        analysisCell.setRowIndex(rowIndex);
        analysisCell.setColumnIndex(columnIndex);
        analysisCell.setOnlyOneVariable(Boolean.TRUE);
        List<String> variableList = new ArrayList<String>();
        analysisCell.setVariableList(variableList);
        List<String> prepareDataList = new ArrayList<String>();
        analysisCell.setPrepareDataList(prepareDataList);
        analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COMMON);
庄家钜's avatar
庄家钜 已提交
445
        analysisCell.setFirstColumn(Boolean.FALSE);
庄家钜's avatar
庄家钜 已提交
446 447 448
        return analysisCell;
    }

庄家钜's avatar
庄家钜 已提交
449 450 451 452 453 454 455
    private String convertPrepareData(String prepareData) {
        prepareData = prepareData.replaceAll(ESCAPE_FILL_PREFIX, FILL_PREFIX);
        prepareData = prepareData.replaceAll(ESCAPE_FILL_SUFFIX, FILL_SUFFIX);
        return prepareData;
    }

}