ExcelWriteFillExecutor.java 23.4 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
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.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;
庄家钜's avatar
庄家钜 已提交
30
import com.alibaba.excel.write.metadata.fill.FillWrapper;
庄家钜's avatar
庄家钜 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
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
     */
51
    private final Map<String, List<AnalysisCell>> templateAnalysisCache = new HashMap<String, List<AnalysisCell>>(8);
庄家钜's avatar
庄家钜 已提交
52 53 54
    /**
     * Collection fields to replace in the template
     */
55
    private final Map<String, List<AnalysisCell>> templateCollectionAnalysisCache =
庄家钜's avatar
庄家钜 已提交
56
        new HashMap<String, List<AnalysisCell>>(8);
庄家钜's avatar
庄家钜 已提交
57 58 59
    /**
     * Style cache for collection fields
     */
60
    private final Map<String, Map<AnalysisCell, CellStyle>> collectionFieldStyleCache =
庄家钜's avatar
庄家钜 已提交
61
        new HashMap<String, Map<AnalysisCell, CellStyle>>(8);
庄家钜's avatar
庄家钜 已提交
62 63 64
    /**
     * Row height cache for collection
     */
65
    private final Map<String, Short> collectionRowHeightCache = new HashMap<String, Short>(8);
庄家钜's avatar
庄家钜 已提交
66 67 68
    /**
     * Last index cache for collection fields
     */
69
    private final Map<String, Map<AnalysisCell, Integer>> collectionLastIndexCache =
庄家钜's avatar
庄家钜 已提交
70
        new HashMap<String, Map<AnalysisCell, Integer>>(8);
庄家钜's avatar
庄家钜 已提交
71

72
    private final Map<String, Integer> relativeRowIndexMap = new HashMap<String, Integer>(8);
庄家钜's avatar
庄家钜 已提交
73 74 75 76 77 78 79 80
    /**
     * The data prefix that is populated this time
     */
    private String currentDataPrefix;
    /**
     * The unique data encoding for this fill
     */
    private String currentUniqueDataFlag;
庄家钜's avatar
庄家钜 已提交
81

庄家钜's avatar
庄家钜 已提交
82 83 84 85 86
    public ExcelWriteFillExecutor(WriteContext writeContext) {
        super(writeContext);
    }

    public void fill(Object data, FillConfig fillConfig) {
87
        if (data == null) {
庄家钜's avatar
庄家钜 已提交
88
            data = new HashMap<String, Object>(16);
89
        }
庄家钜's avatar
庄家钜 已提交
90 91 92 93
        if (fillConfig == null) {
            fillConfig = FillConfig.builder().build(true);
        }
        fillConfig.init();
庄家钜's avatar
庄家钜 已提交
94 95 96

        Object realData;
        if (data instanceof FillWrapper) {
97
            FillWrapper fillWrapper = (FillWrapper) data;
庄家钜's avatar
庄家钜 已提交
98 99 100 101 102 103
            currentDataPrefix = fillWrapper.getName();
            realData = fillWrapper.getCollectionData();
        } else {
            realData = data;
            currentDataPrefix = null;
        }
庄家钜's avatar
庄家钜 已提交
104
        currentUniqueDataFlag = uniqueDataFlag(writeContext.writeSheetHolder(), currentDataPrefix);
庄家钜's avatar
庄家钜 已提交
105 106 107

        // processing data
        if (realData instanceof Collection) {
庄家钜's avatar
庄家钜 已提交
108
            List<AnalysisCell> analysisCellList = readTemplateData(templateCollectionAnalysisCache);
109
            Collection collectionData = (Collection) realData;
庄家钜's avatar
庄家钜 已提交
110 111 112 113 114 115 116 117
            if (CollectionUtils.isEmpty(collectionData)) {
                return;
            }
            Iterator iterator = collectionData.iterator();
            if (WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection()) && fillConfig.getForceNewRow()) {
                shiftRows(collectionData.size(), analysisCellList);
            }
            while (iterator.hasNext()) {
庄家钜's avatar
庄家钜 已提交
118
                doFill(analysisCellList, iterator.next(), fillConfig, getRelativeRowIndex());
庄家钜's avatar
庄家钜 已提交
119 120
            }
        } else {
庄家钜's avatar
庄家钜 已提交
121
            doFill(readTemplateData(templateAnalysisCache), realData, fillConfig, null);
庄家钜's avatar
庄家钜 已提交
122 123 124 125 126 127 128 129
        }
    }

    private void shiftRows(int size, List<AnalysisCell> analysisCellList) {
        if (CollectionUtils.isEmpty(analysisCellList)) {
            return;
        }
        int maxRowIndex = 0;
庄家钜's avatar
庄家钜 已提交
130
        Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(currentUniqueDataFlag);
庄家钜's avatar
庄家钜 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
        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--;
        }
155 156 157
        if (number <= 0) {
            return;
        }
庄家钜's avatar
庄家钜 已提交
158
        sheet.shiftRows(maxRowIndex + 1, lastRowIndex, number, true, false);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

        // The current data is greater than unity rowindex increase
        String tablePrefix = tablePrefix(currentUniqueDataFlag);
        increaseRowIndex(templateAnalysisCache, number, maxRowIndex, tablePrefix);
        increaseRowIndex(templateCollectionAnalysisCache, number, maxRowIndex, tablePrefix);
    }

    private void increaseRowIndex(Map<String, List<AnalysisCell>> templateAnalysisCache, int number, int maxRowIndex,
        String tablePrefix) {
        for (Map.Entry<String, List<AnalysisCell>> entry : templateAnalysisCache.entrySet()) {
            if (!tablePrefix.equals(tablePrefix(entry.getKey()))) {
                continue;
            }
            for (AnalysisCell analysisCell : entry.getValue()) {
                if (analysisCell.getRowIndex() > maxRowIndex) {
                    analysisCell.setRowIndex(analysisCell.getRowIndex() + number);
                }
庄家钜's avatar
庄家钜 已提交
176 177 178 179
            }
        }
    }

庄家钜's avatar
庄家钜 已提交
180 181
    private void doFill(List<AnalysisCell> analysisCellList, Object oneRowData, FillConfig fillConfig,
        Integer relativeRowIndex) {
庄家钜's avatar
庄家钜 已提交
182 183
        Map dataMap;
        if (oneRowData instanceof Map) {
184
            dataMap = (Map) oneRowData;
庄家钜's avatar
庄家钜 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        } 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);
                if (!dataMap.containsKey(variable)) {
                    continue;
                }
                Object value = dataMap.get(variable);
                CellData cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), cell,
200
                    value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex);
庄家钜's avatar
庄家钜 已提交
201
                WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE);
庄家钜's avatar
庄家钜 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214
            } 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++));
                    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);
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
                    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
庄家钜 已提交
230 231 232 233
                    }
                }
                cellValueBuild.append(analysisCell.getPrepareDataList().get(index));
                cell.setCellValue(cellValueBuild.toString());
庄家钜's avatar
庄家钜 已提交
234 235
                WriteHandlerUtils.afterCellDispose(writeContext, cellDataList, cell, null, relativeRowIndex,
                    Boolean.FALSE);
庄家钜's avatar
庄家钜 已提交
236 237 238 239
            }
        }
    }

庄家钜's avatar
庄家钜 已提交
240
    private Integer getRelativeRowIndex() {
庄家钜's avatar
庄家钜 已提交
241
        Integer relativeRowIndex = relativeRowIndexMap.get(currentUniqueDataFlag);
庄家钜's avatar
庄家钜 已提交
242 243 244 245 246
        if (relativeRowIndex == null) {
            relativeRowIndex = 0;
        } else {
            relativeRowIndex++;
        }
庄家钜's avatar
庄家钜 已提交
247
        relativeRowIndexMap.put(currentUniqueDataFlag, relativeRowIndex);
庄家钜's avatar
庄家钜 已提交
248 249 250
        return relativeRowIndex;
    }

庄家钜's avatar
庄家钜 已提交
251 252 253 254 255 256 257
    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());
        }
        Sheet sheet = writeContext.writeSheetHolder().getSheet();

庄家钜's avatar
庄家钜 已提交
258
        Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(currentUniqueDataFlag);
庄家钜's avatar
庄家钜 已提交
259 260
        if (collectionLastIndexMap == null) {
            collectionLastIndexMap = new HashMap<AnalysisCell, Integer>(16);
庄家钜's avatar
庄家钜 已提交
261
            collectionLastIndexCache.put(currentUniqueDataFlag, collectionLastIndexMap);
庄家钜's avatar
庄家钜 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        }
        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.");
        }
庄家钜's avatar
庄家钜 已提交
292 293 294

        Row row = createRowIfNecessary(sheet, cachedSheet, lastRowIndex, fillConfig, analysisCell, isOriginalCell);
        Cell cell = createCellIfNecessary(row,lastColumnIndex);
庄家钜's avatar
庄家钜 已提交
295

庄家钜's avatar
庄家钜 已提交
296
        Map<AnalysisCell, CellStyle> collectionFieldStyleMap = collectionFieldStyleCache.get(currentUniqueDataFlag);
庄家钜's avatar
庄家钜 已提交
297 298
        if (collectionFieldStyleMap == null) {
            collectionFieldStyleMap = new HashMap<AnalysisCell, CellStyle>(16);
庄家钜's avatar
庄家钜 已提交
299
            collectionFieldStyleCache.put(currentUniqueDataFlag, collectionFieldStyleMap);
庄家钜's avatar
庄家钜 已提交
300 301 302 303 304 305 306 307 308 309 310 311
        }
        if (isOriginalCell) {
            collectionFieldStyleMap.put(analysisCell, cell.getCellStyle());
        } else {
            CellStyle cellStyle = collectionFieldStyleMap.get(analysisCell);
            if (cellStyle != null) {
                cell.setCellStyle(cellStyle);
            }
        }
        return cell;
    }

庄家钜's avatar
庄家钜 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    private Cell createCellIfNecessary(Row row, Integer lastColumnIndex) {
        Cell cell = row.getCell(lastColumnIndex);
        if (cell != null) {
            return cell;
        }
        WriteHandlerUtils.beforeCellCreate(writeContext, row, null, lastColumnIndex, null, Boolean.FALSE);
        cell = row.createCell(lastColumnIndex);
        WriteHandlerUtils.afterCellCreate(writeContext, cell, null, null, Boolean.FALSE);
        return cell;
    }

    private Row createRowIfNecessary(Sheet sheet, Sheet cachedSheet, Integer lastRowIndex, FillConfig fillConfig,
        AnalysisCell analysisCell, boolean isOriginalCell) {
        Row row = sheet.getRow(lastRowIndex);
        if (row != null) {
            return row;
        }
        row = cachedSheet.getRow(lastRowIndex);
        if (row == null) {
            WriteHandlerUtils.beforeRowCreate(writeContext, lastRowIndex, null, Boolean.FALSE);
            if (fillConfig.getForceNewRow()) {
                row = cachedSheet.createRow(lastRowIndex);
            } else {
                // The last row of the middle disk inside empty rows, resulting in cachedSheet can not get inside.
                // Will throw Attempting to write a row[" + rownum + "] " + "in the range [0," + this._sh.getLastRowNum() + "] that is already written to disk.
                try {
                    row = sheet.createRow(lastRowIndex);
                } catch (IllegalArgumentException ignore) {
                    row = cachedSheet.createRow(lastRowIndex);
                }
            }
            checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
            WriteHandlerUtils.afterRowCreate(writeContext, row, null, Boolean.FALSE);
        } else {
            checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
        }
        return row;
    }

庄家钜's avatar
庄家钜 已提交
351 352
    private void checkRowHeight(AnalysisCell analysisCell, FillConfig fillConfig, boolean isOriginalCell, Row row) {
        if (!analysisCell.getFirstRow() || !WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection())) {
庄家钜's avatar
庄家钜 已提交
353 354 355
            return;
        }
        if (isOriginalCell) {
庄家钜's avatar
庄家钜 已提交
356
            collectionRowHeightCache.put(currentUniqueDataFlag, row.getHeight());
庄家钜's avatar
庄家钜 已提交
357 358
            return;
        }
庄家钜's avatar
庄家钜 已提交
359
        Short rowHeight = collectionRowHeightCache.get(currentUniqueDataFlag);
庄家钜's avatar
庄家钜 已提交
360 361 362 363 364
        if (rowHeight != null) {
            row.setHeight(rowHeight);
        }
    }

庄家钜's avatar
庄家钜 已提交
365 366
    private List<AnalysisCell> readTemplateData(Map<String, List<AnalysisCell>> analysisCache) {
        List<AnalysisCell> analysisCellList = analysisCache.get(currentUniqueDataFlag);
庄家钜's avatar
庄家钜 已提交
367 368 369 370
        if (analysisCellList != null) {
            return analysisCellList;
        }
        Sheet sheet = writeContext.writeSheetHolder().getCachedSheet();
庄家钜's avatar
庄家钜 已提交
371
        Map<String, Set<Integer>> firstRowCache = new HashMap<String, Set<Integer>>(8);
庄家钜's avatar
庄家钜 已提交
372 373 374 375 376 377 378 379 380 381
        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
庄家钜 已提交
382
                String preparedData = prepareData(cell, i, j, firstRowCache);
庄家钜's avatar
庄家钜 已提交
383
                // Prevent empty data from not being replaced
384 385
                if (preparedData != null) {
                    cell.setCellValue(preparedData);
庄家钜's avatar
庄家钜 已提交
386
                }
庄家钜's avatar
庄家钜 已提交
387 388
            }
        }
庄家钜's avatar
庄家钜 已提交
389
        return analysisCache.get(currentUniqueDataFlag);
庄家钜's avatar
庄家钜 已提交
390 391
    }

庄家钜's avatar
庄家钜 已提交
392
    /**
庄家钜's avatar
庄家钜 已提交
393
     * To prepare data
庄家钜's avatar
庄家钜 已提交
394
     *
395
     * @param cell
庄家钜's avatar
庄家钜 已提交
396 397
     * @param rowIndex
     * @param columnIndex
庄家钜's avatar
庄家钜 已提交
398
     * @param firstRowCache
399
     * @return Returns the data that the cell needs to replace
庄家钜's avatar
庄家钜 已提交
400
     */
庄家钜's avatar
庄家钜 已提交
401
    private String prepareData(Cell cell, int rowIndex, int columnIndex, Map<String, Set<Integer>> firstRowCache) {
402 403 404 405
        if (!CellType.STRING.equals(cell.getCellTypeEnum())) {
            return null;
        }
        String value = cell.getStringCellValue();
庄家钜's avatar
庄家钜 已提交
406
        if (StringUtils.isEmpty(value)) {
407
            return null;
庄家钜's avatar
庄家钜 已提交
408
        }
409
        StringBuilder preparedData = new StringBuilder();
庄家钜's avatar
庄家钜 已提交
410
        AnalysisCell analysisCell = null;
庄家钜's avatar
庄家钜 已提交
411

庄家钜's avatar
庄家钜 已提交
412 413 414
        int startIndex = 0;
        int length = value.length();
        int lastPrepareDataIndex = 0;
415
        out: while (startIndex < length) {
庄家钜's avatar
庄家钜 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
            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
庄家钜 已提交
440
                analysisCell = initAnalysisCell(rowIndex, columnIndex);
庄家钜's avatar
庄家钜 已提交
441 442 443 444 445
            }
            String variable = value.substring(prefixIndex + 1, suffixIndex);
            if (StringUtils.isEmpty(variable)) {
                continue;
            }
庄家钜's avatar
庄家钜 已提交
446 447 448 449 450 451
            int collectPrefixIndex = variable.indexOf(COLLECTION_PREFIX);
            if (collectPrefixIndex > -1) {
                if (collectPrefixIndex != 0) {
                    analysisCell.setPrefix(variable.substring(0, collectPrefixIndex));
                }
                variable = variable.substring(collectPrefixIndex + 1);
庄家钜's avatar
庄家钜 已提交
452 453 454 455 456 457 458 459 460
                if (StringUtils.isEmpty(variable)) {
                    continue;
                }
                analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COLLECTION);
            }
            analysisCell.getVariableList().add(variable);
            if (lastPrepareDataIndex == prefixIndex) {
                analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
            } else {
461 462 463
                String data = convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex));
                preparedData.append(data);
                analysisCell.getPrepareDataList().add(data);
庄家钜's avatar
庄家钜 已提交
464 465 466 467
                analysisCell.setOnlyOneVariable(Boolean.FALSE);
            }
            lastPrepareDataIndex = suffixIndex + 1;
        }
庄家钜's avatar
庄家钜 已提交
468 469
        return dealAnalysisCell(analysisCell, value, rowIndex, lastPrepareDataIndex, length, firstRowCache,
            preparedData);
庄家钜's avatar
庄家钜 已提交
470 471 472
    }

    private String dealAnalysisCell(AnalysisCell analysisCell, String value, int rowIndex, int lastPrepareDataIndex,
庄家钜's avatar
庄家钜 已提交
473
        int length, Map<String, Set<Integer>> firstRowCache, StringBuilder preparedData) {
庄家钜's avatar
庄家钜 已提交
474 475 476 477 478 479 480
        if (analysisCell != null) {
            if (lastPrepareDataIndex == length) {
                analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
            } else {
                analysisCell.getPrepareDataList().add(convertPrepareData(value.substring(lastPrepareDataIndex)));
                analysisCell.setOnlyOneVariable(Boolean.FALSE);
            }
庄家钜's avatar
庄家钜 已提交
481
            String uniqueDataFlag = uniqueDataFlag(writeContext.writeSheetHolder(), analysisCell.getPrefix());
庄家钜's avatar
庄家钜 已提交
482
            if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) {
庄家钜's avatar
庄家钜 已提交
483 484 485 486 487
                List<AnalysisCell> analysisCellList = templateAnalysisCache.get(uniqueDataFlag);
                if (analysisCellList == null) {
                    analysisCellList = new ArrayList<AnalysisCell>();
                    templateAnalysisCache.put(uniqueDataFlag, analysisCellList);
                }
庄家钜's avatar
庄家钜 已提交
488 489
                analysisCellList.add(analysisCell);
            } else {
庄家钜's avatar
庄家钜 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503
                Set<Integer> uniqueFirstRowCache = firstRowCache.get(uniqueDataFlag);
                if (uniqueFirstRowCache == null) {
                    uniqueFirstRowCache = new HashSet<Integer>();
                    firstRowCache.put(uniqueDataFlag, uniqueFirstRowCache);
                }
                if (!uniqueFirstRowCache.contains(rowIndex)) {
                    analysisCell.setFirstRow(Boolean.TRUE);
                    uniqueFirstRowCache.add(rowIndex);
                }

                List<AnalysisCell> collectionAnalysisCellList = templateCollectionAnalysisCache.get(uniqueDataFlag);
                if (collectionAnalysisCellList == null) {
                    collectionAnalysisCellList = new ArrayList<AnalysisCell>();
                    templateCollectionAnalysisCache.put(uniqueDataFlag, collectionAnalysisCellList);
庄家钜's avatar
庄家钜 已提交
504
                }
庄家钜's avatar
庄家钜 已提交
505 506
                collectionAnalysisCellList.add(analysisCell);
            }
507
            return preparedData.toString();
庄家钜's avatar
庄家钜 已提交
508
        }
509
        return null;
庄家钜's avatar
庄家钜 已提交
510 511
    }

庄家钜's avatar
庄家钜 已提交
512 513 514 515 516 517 518 519 520 521
    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
庄家钜 已提交
522
        analysisCell.setFirstRow(Boolean.FALSE);
庄家钜's avatar
庄家钜 已提交
523 524 525
        return analysisCell;
    }

庄家钜's avatar
庄家钜 已提交
526 527 528 529 530 531
    private String convertPrepareData(String prepareData) {
        prepareData = prepareData.replaceAll(ESCAPE_FILL_PREFIX, FILL_PREFIX);
        prepareData = prepareData.replaceAll(ESCAPE_FILL_SUFFIX, FILL_SUFFIX);
        return prepareData;
    }

庄家钜's avatar
庄家钜 已提交
532 533 534 535 536 537 538
    private String uniqueDataFlag(WriteSheetHolder writeSheetHolder, String wrapperName) {
        String prefix;
        if (writeSheetHolder.getSheetNo() != null) {
            prefix = writeSheetHolder.getSheetNo().toString();
        } else {
            prefix = writeSheetHolder.getSheetName().toString();
        }
庄家钜's avatar
庄家钜 已提交
539
        if (StringUtils.isEmpty(wrapperName)) {
庄家钜's avatar
庄家钜 已提交
540
            return prefix + "-";
庄家钜's avatar
庄家钜 已提交
541
        }
庄家钜's avatar
庄家钜 已提交
542
        return prefix + "-" + wrapperName;
庄家钜's avatar
庄家钜 已提交
543 544
    }

545 546 547 548
    private String tablePrefix(String uniqueDataFlag) {
        return uniqueDataFlag.substring(0, uniqueDataFlag.indexOf("-") + 1);
    }

庄家钜's avatar
庄家钜 已提交
549
}