repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/cache/MapCache.java | easyexcel-core/src/main/java/com/alibaba/excel/cache/MapCache.java | package com.alibaba.excel.cache;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
/**
* Putting temporary data directly into a map is a little more efficient but very memory intensive
*
* @author Jiaju Zhuang
*/
public class MapCache implements ReadCache {
private final List<String> cache = new ArrayList<>();
@Override
public void init(AnalysisContext analysisContext) {}
@Override
public void put(String value) {
cache.add(value);
}
@Override
public String get(Integer key) {
if (key == null || key < 0) {
return null;
}
return cache.get(key);
}
@Override
public void putFinished() {}
@Override
public void destroy() {}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/cache/ReadCache.java | easyexcel-core/src/main/java/com/alibaba/excel/cache/ReadCache.java | package com.alibaba.excel.cache;
import com.alibaba.excel.context.AnalysisContext;
/**
* Read cache
*
* @author Jiaju Zhuang
*/
public interface ReadCache {
/**
* Initialize cache
*
* @param analysisContext
* A context is the main anchorage point of a excel reader.
*/
void init(AnalysisContext analysisContext);
/**
* Automatically generate the key and put it in the cache.Key start from 0
*
* @param value
* Cache value
*/
void put(String value);
/**
* Get value
*
* @param key
* Index
* @return Value
*/
String get(Integer key);
/**
* It's called when all the values are put in
*/
void putFinished();
/**
* Called when the excel read is complete
*/
void destroy();
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/cache/XlsCache.java | easyexcel-core/src/main/java/com/alibaba/excel/cache/XlsCache.java | package com.alibaba.excel.cache;
import org.apache.poi.hssf.record.SSTRecord;
import com.alibaba.excel.context.AnalysisContext;
/**
*
* Use SSTRecord.
*
* @author Jiaju Zhuang
*/
public class XlsCache implements ReadCache {
private final SSTRecord sstRecord;
public XlsCache(SSTRecord sstRecord) {
this.sstRecord = sstRecord;
}
@Override
public void init(AnalysisContext analysisContext) {}
@Override
public void put(String value) {}
@Override
public String get(Integer key) {
return sstRecord.getString(key).toString();
}
@Override
public void putFinished() {}
@Override
public void destroy() {}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/cache/selector/EternalReadCacheSelector.java | easyexcel-core/src/main/java/com/alibaba/excel/cache/selector/EternalReadCacheSelector.java | package com.alibaba.excel.cache.selector;
import org.apache.poi.openxml4j.opc.PackagePart;
import com.alibaba.excel.cache.ReadCache;
/**
* Choose a eternal cache
*
* @author Jiaju Zhuang
**/
public class EternalReadCacheSelector implements ReadCacheSelector {
private ReadCache readCache;
public EternalReadCacheSelector(ReadCache readCache) {
this.readCache = readCache;
}
@Override
public ReadCache readCache(PackagePart sharedStringsTablePackagePart) {
return readCache;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/cache/selector/SimpleReadCacheSelector.java | easyexcel-core/src/main/java/com/alibaba/excel/cache/selector/SimpleReadCacheSelector.java | package com.alibaba.excel.cache.selector;
import java.io.IOException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.cache.Ehcache;
import com.alibaba.excel.cache.MapCache;
import com.alibaba.excel.cache.ReadCache;
/**
* Simple cache selector
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class SimpleReadCacheSelector implements ReadCacheSelector {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleReadCacheSelector.class);
/**
* Convert bytes to megabytes
*/
private static final long B2M = 1000 * 1000L;
/**
* If it's less than 5M, use map cache, or use ehcache.unit MB.
*/
private static final long DEFAULT_MAX_USE_MAP_CACHE_SIZE = 5;
/**
* Maximum batch of `SharedStrings` stored in memory.
* The batch size is 100.{@link Ehcache#BATCH_COUNT}
*/
private static final int DEFAULT_MAX_EHCACHE_ACTIVATE_BATCH_COUNT = 20;
/**
* Shared strings exceeding this value will use {@link Ehcache},or use {@link MapCache}.unit MB.
*/
private Long maxUseMapCacheSize;
/**
* Maximum size of cache activation.unit MB.
*
* @deprecated Please use maxCacheActivateBatchCount to control the size of the occupied memory
*/
@Deprecated
private Integer maxCacheActivateSize;
/**
* Maximum batch of `SharedStrings` stored in memory.
* The batch size is 100.{@link Ehcache#BATCH_COUNT}
*/
private Integer maxCacheActivateBatchCount;
public SimpleReadCacheSelector() {
}
/**
* Parameter maxCacheActivateSize has already been abandoned
*
* @param maxUseMapCacheSize
* @param maxCacheActivateSize
*/
@Deprecated
public SimpleReadCacheSelector(Long maxUseMapCacheSize, Integer maxCacheActivateSize) {
this.maxUseMapCacheSize = maxUseMapCacheSize;
this.maxCacheActivateSize = maxCacheActivateSize;
}
@Override
public ReadCache readCache(PackagePart sharedStringsTablePackagePart) {
long size = sharedStringsTablePackagePart.getSize();
if (size < 0) {
try {
size = sharedStringsTablePackagePart.getInputStream().available();
} catch (IOException e) {
LOGGER.warn("Unable to get file size, default used MapCache");
return new MapCache();
}
}
if (maxUseMapCacheSize == null) {
maxUseMapCacheSize = DEFAULT_MAX_USE_MAP_CACHE_SIZE;
}
if (size < maxUseMapCacheSize * B2M) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Use map cache.size:{}", size);
}
return new MapCache();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Use ehcache.size:{}", size);
}
// In order to be compatible with the code
// If the user set up `maxCacheActivateSize`, then continue using it
if (maxCacheActivateSize != null) {
return new Ehcache(maxCacheActivateSize, maxCacheActivateBatchCount);
} else {
if (maxCacheActivateBatchCount == null) {
maxCacheActivateBatchCount = DEFAULT_MAX_EHCACHE_ACTIVATE_BATCH_COUNT;
}
return new Ehcache(maxCacheActivateSize, maxCacheActivateBatchCount);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/cache/selector/ReadCacheSelector.java | easyexcel-core/src/main/java/com/alibaba/excel/cache/selector/ReadCacheSelector.java | package com.alibaba.excel.cache.selector;
import org.apache.poi.openxml4j.opc.PackagePart;
import com.alibaba.excel.cache.ReadCache;
/**
* Select the cache
*
* @author Jiaju Zhuang
**/
public interface ReadCacheSelector {
/**
* Select a cache
*
* @param sharedStringsTablePackagePart
* @return
*/
ReadCache readCache(PackagePart sharedStringsTablePackagePart);
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelCommonException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelCommonException.java | package com.alibaba.excel.exception;
/**
*
* @author Jiaju Zhuang
*/
public class ExcelCommonException extends ExcelRuntimeException {
public ExcelCommonException() {}
public ExcelCommonException(String message) {
super(message);
}
public ExcelCommonException(String message, Throwable cause) {
super(message, cause);
}
public ExcelCommonException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopSheetException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopSheetException.java | package com.alibaba.excel.exception;
/**
* Throw the exception when you need to stop
* This exception will only stop the parsing of the current sheet. If you want to stop the entire excel parsing, please
* use ExcelAnalysisStopException.
*
* The com.alibaba.excel.read.listener.ReadListener#doAfterAllAnalysed(com.alibaba.excel.context.AnalysisContext) method
* is called after the call is stopped.
*
* @author Jiaju Zhuang
* @see ExcelAnalysisStopException
* @since 3.3.4
*/
public class ExcelAnalysisStopSheetException extends ExcelAnalysisException {
public ExcelAnalysisStopSheetException() {}
public ExcelAnalysisStopSheetException(String message) {
super(message);
}
public ExcelAnalysisStopSheetException(String message, Throwable cause) {
super(message, cause);
}
public ExcelAnalysisStopSheetException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java | package com.alibaba.excel.exception;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Data convert exception
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class ExcelDataConvertException extends ExcelRuntimeException {
/**
* NotNull.
*/
private Integer rowIndex;
/**
* NotNull.
*/
private Integer columnIndex;
/**
* NotNull.
*/
private CellData<?> cellData;
/**
* Nullable.Only when the header is configured and when the class header is used is not null.
*
* @see ExcelWriterBuilder#head(Class)
*/
private ExcelContentProperty excelContentProperty;
public ExcelDataConvertException(Integer rowIndex, Integer columnIndex, CellData<?> cellData,
ExcelContentProperty excelContentProperty, String message) {
super(message);
this.rowIndex = rowIndex;
this.columnIndex = columnIndex;
this.cellData = cellData;
this.excelContentProperty = excelContentProperty;
}
public ExcelDataConvertException(Integer rowIndex, Integer columnIndex, CellData<?> cellData,
ExcelContentProperty excelContentProperty, String message, Throwable cause) {
super(message, cause);
this.rowIndex = rowIndex;
this.columnIndex = columnIndex;
this.cellData = cellData;
this.excelContentProperty = excelContentProperty;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopException.java | package com.alibaba.excel.exception;
/**
* Throw the exception when you need to stop
* This exception will stop the entire excel parsing. If you only want to stop the parsing of a certain sheet, please
* use ExcelAnalysisStopSheetException.
*
* @author Jiaju Zhuang
* @see ExcelAnalysisStopException
*/
public class ExcelAnalysisStopException extends ExcelAnalysisException {
public ExcelAnalysisStopException() {}
public ExcelAnalysisStopException(String message) {
super(message);
}
public ExcelAnalysisStopException(String message, Throwable cause) {
super(message, cause);
}
public ExcelAnalysisStopException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java | package com.alibaba.excel.exception;
/**
* @author jipengfei
*/
public class ExcelGenerateException extends ExcelRuntimeException {
public ExcelGenerateException(String message) {
super(message);
}
public ExcelGenerateException(String message, Throwable cause) {
super(message, cause);
}
public ExcelGenerateException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelRuntimeException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelRuntimeException.java | package com.alibaba.excel.exception;
/**
* Excel Exception
* @author Jiaju Zhuang
*/
public class ExcelRuntimeException extends RuntimeException {
public ExcelRuntimeException() {}
public ExcelRuntimeException(String message) {
super(message);
}
public ExcelRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public ExcelRuntimeException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelAnalysisException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelAnalysisException.java | package com.alibaba.excel.exception;
/**
*
* @author jipengfei
*/
public class ExcelAnalysisException extends ExcelRuntimeException {
public ExcelAnalysisException() {}
public ExcelAnalysisException(String message) {
super(message);
}
public ExcelAnalysisException(String message, Throwable cause) {
super(message, cause);
}
public ExcelAnalysisException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelWriteDataConvertException.java | easyexcel-core/src/main/java/com/alibaba/excel/exception/ExcelWriteDataConvertException.java | package com.alibaba.excel.exception;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Data convert exception
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class ExcelWriteDataConvertException extends ExcelDataConvertException {
/**
* handler.
*/
private CellWriteHandlerContext cellWriteHandlerContext;
public ExcelWriteDataConvertException(CellWriteHandlerContext cellWriteHandlerContext, String message) {
super(cellWriteHandlerContext.getRowIndex(), cellWriteHandlerContext.getColumnIndex(),
cellWriteHandlerContext.getFirstCellData(), cellWriteHandlerContext.getExcelContentProperty(), message);
this.cellWriteHandlerContext = cellWriteHandlerContext;
}
public ExcelWriteDataConvertException(CellWriteHandlerContext cellWriteHandlerContext, String message,
Throwable cause) {
super(cellWriteHandlerContext.getRowIndex(), cellWriteHandlerContext.getColumnIndex(),
cellWriteHandlerContext.getFirstCellData(), cellWriteHandlerContext.getExcelContentProperty(), message,
cause);
this.cellWriteHandlerContext = cellWriteHandlerContext;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java | easyexcel-core/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java | package com.alibaba.excel.write;
import java.util.Collection;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.context.WriteContextImpl;
import com.alibaba.excel.enums.WriteTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.write.executor.ExcelWriteAddExecutor;
import com.alibaba.excel.write.executor.ExcelWriteFillExecutor;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import org.apache.poi.ss.util.CellRangeAddress;
/**
* @author jipengfei
*/
public class ExcelBuilderImpl implements ExcelBuilder {
private final WriteContext context;
private ExcelWriteFillExecutor excelWriteFillExecutor;
private ExcelWriteAddExecutor excelWriteAddExecutor;
static {
// Create temporary cache directory at initialization time to avoid POI concurrent write bugs
FileUtils.createPoiFilesDirectory();
}
public ExcelBuilderImpl(WriteWorkbook writeWorkbook) {
try {
context = new WriteContextImpl(writeWorkbook);
} catch (RuntimeException e) {
finishOnException();
throw e;
} catch (Throwable e) {
finishOnException();
throw new ExcelGenerateException(e);
}
}
@Override
public void addContent(Collection<?> data, WriteSheet writeSheet) {
addContent(data, writeSheet, null);
}
@Override
public void addContent(Collection<?> data, WriteSheet writeSheet, WriteTable writeTable) {
try {
context.currentSheet(writeSheet, WriteTypeEnum.ADD);
context.currentTable(writeTable);
if (excelWriteAddExecutor == null) {
excelWriteAddExecutor = new ExcelWriteAddExecutor(context);
}
excelWriteAddExecutor.add(data);
} catch (RuntimeException e) {
finishOnException();
throw e;
} catch (Throwable e) {
finishOnException();
throw new ExcelGenerateException(e);
}
}
@Override
public void fill(Object data, FillConfig fillConfig, WriteSheet writeSheet) {
try {
if (context.writeWorkbookHolder().getTempTemplateInputStream() == null) {
throw new ExcelGenerateException("Calling the 'fill' method must use a template.");
}
if (context.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.CSV) {
throw new ExcelGenerateException("csv does not support filling data.");
}
context.currentSheet(writeSheet, WriteTypeEnum.FILL);
if (excelWriteFillExecutor == null) {
excelWriteFillExecutor = new ExcelWriteFillExecutor(context);
}
excelWriteFillExecutor.fill(data, fillConfig);
} catch (RuntimeException e) {
finishOnException();
throw e;
} catch (Throwable e) {
finishOnException();
throw new ExcelGenerateException(e);
}
}
private void finishOnException() {
finish(true);
}
@Override
public void finish(boolean onException) {
if (context != null) {
context.finish(onException);
}
}
@Override
public void merge(int firstRow, int lastRow, int firstCol, int lastCol) {
CellRangeAddress cra = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
context.writeSheetHolder().getSheet().addMergedRegion(cra);
}
@Override
public WriteContext writeContext() {
return context;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/ExcelBuilder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/ExcelBuilder.java | package com.alibaba.excel.write;
import java.util.Collection;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.fill.FillConfig;
/**
* @author jipengfei
*/
public interface ExcelBuilder {
/**
* WorkBook increase value
*
* @param data
* java basic type or java model extend BaseModel
* @param writeSheet
* Write the sheet
* @deprecated please use{@link ExcelBuilder#addContent(Collection, WriteSheet, WriteTable)}
*/
@Deprecated
void addContent(Collection<?> data, WriteSheet writeSheet);
/**
* WorkBook increase value
*
* @param data
* java basic type or java model extend BaseModel
* @param writeSheet
* Write the sheet
* @param writeTable
* Write the table
*/
void addContent(Collection<?> data, WriteSheet writeSheet, WriteTable writeTable);
/**
* WorkBook fill value
*
* @param data
* @param fillConfig
* @param writeSheet
*/
void fill(Object data, FillConfig fillConfig, WriteSheet writeSheet);
/**
* Creates new cell range. Indexes are zero-based.
*
* @param firstRow
* Index of first row
* @param lastRow
* Index of last row (inclusive), must be equal to or larger than {@code firstRow}
* @param firstCol
* Index of first column
* @param lastCol
* Index of last column (inclusive), must be equal to or larger than {@code firstCol}
* @deprecated please use{@link OnceAbsoluteMergeStrategy}
*/
@Deprecated
void merge(int firstRow, int lastRow, int firstCol, int lastCol);
/**
* Gets the written data
*
* @return
*/
WriteContext writeContext();
/**
* Close io
*
* @param onException
*/
void finish(boolean onException);
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java | package com.alibaba.excel.write.metadata;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Workbook
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class WriteWorkbook extends WriteBasicParameter {
/**
* Excel type.The default is xlsx
*/
private ExcelTypeEnum excelType;
/**
* Final output file
* <p>
* If 'outputStream' and 'file' all not empty, file first
*/
private File file;
/**
* Final output stream
* <p>
* If 'outputStream' and 'file' all not empty, file first
*/
private OutputStream outputStream;
/**
* charset.
* Only work on the CSV file
*/
private Charset charset;
/**
* Set the encoding prefix in the csv file, otherwise the office may open garbled characters.
* Default true.
*/
private Boolean withBom;
/**
* Template input stream
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private InputStream templateInputStream;
/**
* Template file.
* This file is read into memory, excessive cases can lead to OOM.
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private File templateFile;
/**
* Default true.
*/
private Boolean autoCloseStream;
/**
* Mandatory use 'inputStream' .Default is false
*/
private Boolean mandatoryUseInputStream;
/**
* Whether the encryption
* <p>
* WARRING:Encryption is when the entire file is read into memory, so it is very memory intensive.
*/
private String password;
/**
* Write excel in memory. Default false, the cache file is created and finally written to excel.
* <p>
* Comment and RichTextString are only supported in memory mode.
*/
private Boolean inMemory;
/**
* Excel is also written in the event of an exception being thrown.The default false.
*/
private Boolean writeExcelOnException;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java | package com.alibaba.excel.write.metadata;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* table
*
* @author jipengfei
*/
@Getter
@Setter
@EqualsAndHashCode
public class WriteTable extends WriteBasicParameter {
/**
* Starting from 0
*/
private Integer tableNo;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/MapRowData.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/MapRowData.java | package com.alibaba.excel.write.metadata;
import java.util.Map;
/**
* A map row of data.
*
* @author Jiaju Zhuang
*/
public class MapRowData implements RowData {
private final Map<Integer, ?> map;
public MapRowData(Map<Integer, ?> map) {
this.map = map;
}
@Override
public Object get(int index) {
return map.get(index);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/RowData.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/RowData.java | package com.alibaba.excel.write.metadata;
/**
* A row of data.
*
* @author Jiaju Zhuang
*/
public interface RowData {
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* @param index
* @return data
*/
Object get(int index);
/**
* Returns the number of elements in this collection. If this collection
* contains more than <code>Integer.MAX_VALUE</code> elements, returns
* <code>Integer.MAX_VALUE</code>.
*
* @return the number of elements in this collection
*/
int size();
/**
* Returns <code>true</code> if this collection contains no elements.
*
* @return <code>true</code> if this collection contains no elements
*/
boolean isEmpty();
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java | package com.alibaba.excel.write.metadata;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Write sheet
*
* @author jipengfei
*/
@Getter
@Setter
@EqualsAndHashCode
public class WriteSheet extends WriteBasicParameter {
/**
* Starting from 0
*/
private Integer sheetNo;
/**
* sheet name
*/
private String sheetName;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java | package com.alibaba.excel.write.metadata;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.alibaba.excel.metadata.BasicParameter;
import com.alibaba.excel.write.handler.WriteHandler;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Write basic parameter
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class WriteBasicParameter extends BasicParameter {
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer relativeHeadRowIndex;
/**
* Need Head
*/
private Boolean needHead;
/**
* Custom type handler override the default
*/
private List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>();
/**
* Use the default style.Default is true.
*/
private Boolean useDefaultStyle;
/**
* Whether to automatically merge headers.Default is true.
*/
private Boolean automaticMergeHead;
/**
* Ignore the custom columns.
*/
private Collection<Integer> excludeColumnIndexes;
/**
* Ignore the custom columns.
*/
private Collection<String> excludeColumnFieldNames;
/**
* Only output the custom columns.
*/
private Collection<Integer> includeColumnIndexes;
/**
* Only output the custom columns.
*/
private Collection<String> includeColumnFieldNames;
/**
* Data will be order by {@link #includeColumnFieldNames} or {@link #includeColumnIndexes}.
*
* default is false.
*/
private Boolean orderByIncludeColumn;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/CollectionRowData.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/CollectionRowData.java | package com.alibaba.excel.write.metadata;
import java.util.Collection;
/**
* A collection row of data.
*
* @author Jiaju Zhuang
*/
public class CollectionRowData implements RowData {
private final Object[] array;
public CollectionRowData(Collection<?> collection) {
this.array = collection.toArray();
}
@Override
public Object get(int index) {
return array[index];
}
@Override
public int size() {
return array.length;
}
@Override
public boolean isEmpty() {
return array.length == 0;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java | package com.alibaba.excel.write.metadata.style;
import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.metadata.property.FontProperty;
import com.alibaba.excel.metadata.property.StyleProperty;
import com.alibaba.excel.util.StringUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IgnoredErrorType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
/**
* Cell style when writing
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class WriteCellStyle {
/**
* Set the data format (must be a valid format). Built in formats are defined at {@link BuiltinFormats}.
*/
private DataFormatData dataFormatData;
/**
* Set the font for this style
*/
private WriteFont writeFont;
/**
* Set the cell's using this style to be hidden
*/
private Boolean hidden;
/**
* Set the cell's using this style to be locked
*/
private Boolean locked;
/**
* Turn on or off "Quote Prefix" or "123 Prefix" for the style, which is used to tell Excel that the thing which
* looks like a number or a formula shouldn't be treated as on. Turning this on is somewhat (but not completely, see
* {@link IgnoredErrorType}) like prefixing the cell value with a ' in Excel
*/
private Boolean quotePrefix;
/**
* Set the type of horizontal alignment for the cell
*/
private HorizontalAlignment horizontalAlignment;
/**
* Set whether the text should be wrapped. Setting this flag to <code>true</code> make all content visible within a
* cell by displaying it on multiple lines
*/
private Boolean wrapped;
/**
* Set the type of vertical alignment for the cell
*/
private VerticalAlignment verticalAlignment;
/**
* Set the degree of rotation for the text in the cell.
*
* Note: HSSF uses values from -90 to 90 degrees, whereas XSSF uses values from 0 to 180 degrees. The
* implementations of this method will map between these two value-ranges accordingly, however the corresponding
* getter is returning values in the range mandated by the current type of Excel file-format that this CellStyle is
* applied to.
*/
private Short rotation;
/**
* Set the number of spaces to indent the text in the cell
*/
private Short indent;
/**
* Set the type of border to use for the left border of the cell
*/
private BorderStyle borderLeft;
/**
* Set the type of border to use for the right border of the cell
*/
private BorderStyle borderRight;
/**
* Set the type of border to use for the top border of the cell
*/
private BorderStyle borderTop;
/**
* Set the type of border to use for the bottom border of the cell
*/
private BorderStyle borderBottom;
/**
* Set the color to use for the left border
*
* @see IndexedColors
*/
private Short leftBorderColor;
/**
* Set the color to use for the right border
*
* @see IndexedColors
*/
private Short rightBorderColor;
/**
* Set the color to use for the top border
*
* @see IndexedColors
*/
private Short topBorderColor;
/**
* Set the color to use for the bottom border
*
* @see IndexedColors
*/
private Short bottomBorderColor;
/**
* Setting to one fills the cell with the foreground color... No idea about other values
*
* @see FillPatternType#SOLID_FOREGROUND
*/
private FillPatternType fillPatternType;
/**
* Set the background fill color.
*
* @see IndexedColors
*/
private Short fillBackgroundColor;
/**
* Set the foreground fill color <i>Note: Ensure Foreground color is set prior to background color.</i>
*
* @see IndexedColors
*/
private Short fillForegroundColor;
/**
* Controls if the Cell should be auto-sized to shrink to fit if the text is too long
*/
private Boolean shrinkToFit;
/**
* The source is not empty merge the data to the target.
*
* @param source source
* @param target target
*/
public static void merge(WriteCellStyle source, WriteCellStyle target) {
if (source == null || target == null) {
return;
}
if (source.getDataFormatData() != null) {
if (target.getDataFormatData() == null) {
target.setDataFormatData(source.getDataFormatData());
} else {
DataFormatData.merge(source.getDataFormatData(), target.getDataFormatData());
}
}
if (source.getWriteFont() != null) {
if (target.getWriteFont() == null) {
target.setWriteFont(source.getWriteFont());
} else {
WriteFont.merge(source.getWriteFont(), target.getWriteFont());
}
}
if (source.getHidden() != null) {
target.setHidden(source.getHidden());
}
if (source.getLocked() != null) {
target.setLocked(source.getLocked());
}
if (source.getQuotePrefix() != null) {
target.setQuotePrefix(source.getQuotePrefix());
}
if (source.getHorizontalAlignment() != null) {
target.setHorizontalAlignment(source.getHorizontalAlignment());
}
if (source.getWrapped() != null) {
target.setWrapped(source.getWrapped());
}
if (source.getVerticalAlignment() != null) {
target.setVerticalAlignment(source.getVerticalAlignment());
}
if (source.getRotation() != null) {
target.setRotation(source.getRotation());
}
if (source.getIndent() != null) {
target.setIndent(source.getIndent());
}
if (source.getBorderLeft() != null) {
target.setBorderLeft(source.getBorderLeft());
}
if (source.getBorderRight() != null) {
target.setBorderRight(source.getBorderRight());
}
if (source.getBorderTop() != null) {
target.setBorderTop(source.getBorderTop());
}
if (source.getBorderBottom() != null) {
target.setBorderBottom(source.getBorderBottom());
}
if (source.getLeftBorderColor() != null) {
target.setLeftBorderColor(source.getLeftBorderColor());
}
if (source.getRightBorderColor() != null) {
target.setRightBorderColor(source.getRightBorderColor());
}
if (source.getTopBorderColor() != null) {
target.setTopBorderColor(source.getTopBorderColor());
}
if (source.getBottomBorderColor() != null) {
target.setBottomBorderColor(source.getBottomBorderColor());
}
if (source.getFillPatternType() != null) {
target.setFillPatternType(source.getFillPatternType());
}
if (source.getFillBackgroundColor() != null) {
target.setFillBackgroundColor(source.getFillBackgroundColor());
}
if (source.getFillForegroundColor() != null) {
target.setFillForegroundColor(source.getFillForegroundColor());
}
if (source.getShrinkToFit() != null) {
target.setShrinkToFit(source.getShrinkToFit());
}
}
/**
* The source is not empty merge the data to the target.
*
* @param styleProperty styleProperty
* @param fontProperty fontProperty
*/
public static WriteCellStyle build(StyleProperty styleProperty, FontProperty fontProperty) {
if (styleProperty == null && fontProperty == null) {
return null;
}
WriteCellStyle writeCellStyle = new WriteCellStyle();
buildStyleProperty(styleProperty, writeCellStyle);
buildFontProperty(fontProperty, writeCellStyle);
return writeCellStyle;
}
private static void buildFontProperty(FontProperty fontProperty, WriteCellStyle writeCellStyle) {
if (fontProperty == null) {
return;
}
if (writeCellStyle.getWriteFont() == null) {
writeCellStyle.setWriteFont(new WriteFont());
}
WriteFont writeFont = writeCellStyle.getWriteFont();
if (StringUtils.isNotBlank(fontProperty.getFontName())) {
writeFont.setFontName(fontProperty.getFontName());
}
if (fontProperty.getFontHeightInPoints() != null) {
writeFont.setFontHeightInPoints(fontProperty.getFontHeightInPoints());
}
if (fontProperty.getItalic() != null) {
writeFont.setItalic(fontProperty.getItalic());
}
if (fontProperty.getStrikeout() != null) {
writeFont.setStrikeout(fontProperty.getStrikeout());
}
if (fontProperty.getColor() != null) {
writeFont.setColor(fontProperty.getColor());
}
if (fontProperty.getTypeOffset() != null) {
writeFont.setTypeOffset(fontProperty.getTypeOffset());
}
if (fontProperty.getUnderline() != null) {
writeFont.setUnderline(fontProperty.getUnderline());
}
if (fontProperty.getCharset() != null) {
writeFont.setCharset(fontProperty.getCharset());
}
if (fontProperty.getBold() != null) {
writeFont.setBold(fontProperty.getBold());
}
}
private static void buildStyleProperty(StyleProperty styleProperty, WriteCellStyle writeCellStyle) {
if (styleProperty == null) {
return;
}
if (styleProperty.getDataFormatData() != null) {
if (writeCellStyle.getDataFormatData() == null) {
writeCellStyle.setDataFormatData(styleProperty.getDataFormatData());
} else {
DataFormatData.merge(styleProperty.getDataFormatData(), writeCellStyle.getDataFormatData());
}
}
if (styleProperty.getHidden() != null) {
writeCellStyle.setHidden(styleProperty.getHidden());
}
if (styleProperty.getLocked() != null) {
writeCellStyle.setLocked(styleProperty.getLocked());
}
if (styleProperty.getQuotePrefix() != null) {
writeCellStyle.setQuotePrefix(styleProperty.getQuotePrefix());
}
if (styleProperty.getHorizontalAlignment() != null) {
writeCellStyle.setHorizontalAlignment(styleProperty.getHorizontalAlignment());
}
if (styleProperty.getWrapped() != null) {
writeCellStyle.setWrapped(styleProperty.getWrapped());
}
if (styleProperty.getVerticalAlignment() != null) {
writeCellStyle.setVerticalAlignment(styleProperty.getVerticalAlignment());
}
if (styleProperty.getRotation() != null) {
writeCellStyle.setRotation(styleProperty.getRotation());
}
if (styleProperty.getIndent() != null) {
writeCellStyle.setIndent(styleProperty.getIndent());
}
if (styleProperty.getBorderLeft() != null) {
writeCellStyle.setBorderLeft(styleProperty.getBorderLeft());
}
if (styleProperty.getBorderRight() != null) {
writeCellStyle.setBorderRight(styleProperty.getBorderRight());
}
if (styleProperty.getBorderTop() != null) {
writeCellStyle.setBorderTop(styleProperty.getBorderTop());
}
if (styleProperty.getBorderBottom() != null) {
writeCellStyle.setBorderBottom(styleProperty.getBorderBottom());
}
if (styleProperty.getLeftBorderColor() != null) {
writeCellStyle.setLeftBorderColor(styleProperty.getLeftBorderColor());
}
if (styleProperty.getRightBorderColor() != null) {
writeCellStyle.setRightBorderColor(styleProperty.getRightBorderColor());
}
if (styleProperty.getTopBorderColor() != null) {
writeCellStyle.setTopBorderColor(styleProperty.getTopBorderColor());
}
if (styleProperty.getBottomBorderColor() != null) {
writeCellStyle.setBottomBorderColor(styleProperty.getBottomBorderColor());
}
if (styleProperty.getFillPatternType() != null) {
writeCellStyle.setFillPatternType(styleProperty.getFillPatternType());
}
if (styleProperty.getFillBackgroundColor() != null) {
writeCellStyle.setFillBackgroundColor(styleProperty.getFillBackgroundColor());
}
if (styleProperty.getFillForegroundColor() != null) {
writeCellStyle.setFillForegroundColor(styleProperty.getFillForegroundColor());
}
if (styleProperty.getShrinkToFit() != null) {
writeCellStyle.setShrinkToFit(styleProperty.getShrinkToFit());
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java | package com.alibaba.excel.write.metadata.style;
import com.alibaba.excel.util.StringUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.common.usermodel.fonts.FontCharset;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
/**
* Font when writing
*
* @author jipengfei
*/
@Getter
@Setter
@EqualsAndHashCode
public class WriteFont {
/**
* The name for the font (i.e. Arial)
*/
private String fontName;
/**
* Height in the familiar unit of measure - points
*/
private Short fontHeightInPoints;
/**
* Whether to use italics or not
*/
private Boolean italic;
/**
* Whether to use a strikeout horizontal line through the text or not
*/
private Boolean strikeout;
/**
* The color for the font
*
* @see Font#COLOR_NORMAL
* @see Font#COLOR_RED
* @see HSSFPalette#getColor(short)
* @see IndexedColors
*/
private Short color;
/**
* Set normal, super or subscript.
*
* @see Font#SS_NONE
* @see Font#SS_SUPER
* @see Font#SS_SUB
*/
private Short typeOffset;
/**
* set type of text underlining to use
*
* @see Font#U_NONE
* @see Font#U_SINGLE
* @see Font#U_DOUBLE
* @see Font#U_SINGLE_ACCOUNTING
* @see Font#U_DOUBLE_ACCOUNTING
*/
private Byte underline;
/**
* Set character-set to use.
*
* @see FontCharset
* @see Font#ANSI_CHARSET
* @see Font#DEFAULT_CHARSET
* @see Font#SYMBOL_CHARSET
*/
private Integer charset;
/**
* Bold
*/
private Boolean bold;
/**
* The source is not empty merge the data to the target.
*
* @param source source
* @param target target
*/
public static void merge(WriteFont source, WriteFont target) {
if (source == null || target == null) {
return;
}
if (StringUtils.isNotBlank(source.getFontName())) {
target.setFontName(source.getFontName());
}
if (source.getFontHeightInPoints() != null) {
target.setFontHeightInPoints(source.getFontHeightInPoints());
}
if (source.getItalic() != null) {
target.setItalic(source.getItalic());
}
if (source.getStrikeout() != null) {
target.setStrikeout(source.getStrikeout());
}
if (source.getColor() != null) {
target.setColor(source.getColor());
}
if (source.getTypeOffset() != null) {
target.setTypeOffset(source.getTypeOffset());
}
if (source.getUnderline() != null) {
target.setUnderline(source.getUnderline());
}
if (source.getCharset() != null) {
target.setCharset(source.getCharset());
}
if (source.getBold() != null) {
target.setBold(source.getBold());
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/fill/FillConfig.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/fill/FillConfig.java | package com.alibaba.excel.write.metadata.fill;
import com.alibaba.excel.enums.WriteDirectionEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Fill config
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class FillConfig {
private WriteDirectionEnum direction;
/**
* Create a new row each time you use the list parameter.The default create if necessary.
* <p>
* Warnning:If you use <code>forceNewRow</code> set true, will not be able to use asynchronous write file, simply
* say the whole file will be stored in memory.
*/
private Boolean forceNewRow;
/**
* Automatically inherit style
*
* default true.
*/
private Boolean autoStyle;
private boolean hasInit;
public void init() {
if (hasInit) {
return;
}
if (direction == null) {
direction = WriteDirectionEnum.VERTICAL;
}
if (forceNewRow == null) {
forceNewRow = Boolean.FALSE;
}
if (autoStyle == null) {
autoStyle = Boolean.TRUE;
}
hasInit = true;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/fill/FillWrapper.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/fill/FillWrapper.java | package com.alibaba.excel.write.metadata.fill;
import java.util.Collection;
/**
* Multiple lists are supported when packing
*
* @author Jiaju Zhuang
**/
public class FillWrapper {
/**
* The collection prefix that needs to be filled.
*/
private String name;
/**
* Data that needs to be filled.
*/
private Collection collectionData;
public FillWrapper(Collection collectionData) {
this.collectionData = collectionData;
}
public FillWrapper(String name, Collection collectionData) {
this.name = name;
this.collectionData = collectionData;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection getCollectionData() {
return collectionData;
}
public void setCollectionData(Collection collectionData) {
this.collectionData = collectionData;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/fill/AnalysisCell.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/fill/AnalysisCell.java | package com.alibaba.excel.write.metadata.fill;
import java.util.List;
import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Read the cells of the template while populating the data.
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class AnalysisCell {
private int columnIndex;
private int rowIndex;
private List<String> variableList;
private List<String> prepareDataList;
private Boolean onlyOneVariable;
private WriteTemplateAnalysisCellTypeEnum cellType;
private String prefix;
private Boolean firstRow;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AnalysisCell that = (AnalysisCell)o;
if (columnIndex != that.columnIndex) {
return false;
}
return rowIndex == that.rowIndex;
}
@Override
public int hashCode() {
int result = columnIndex;
result = 31 * result + rowIndex;
return result;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java | package com.alibaba.excel.write.metadata.holder;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.write.metadata.WriteTable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* sheet holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class WriteTableHolder extends AbstractWriteHolder {
/***
* poi sheet
*/
private WriteSheetHolder parentWriteSheetHolder;
/***
* tableNo
*/
private Integer tableNo;
/**
* current table param
*/
private WriteTable writeTable;
public WriteTableHolder(WriteTable writeTable, WriteSheetHolder writeSheetHolder) {
super(writeTable, writeSheetHolder);
this.parentWriteSheetHolder = writeSheetHolder;
this.tableNo = writeTable.getTableNo();
this.writeTable = writeTable;
// init handler
initHandler(writeTable, writeSheetHolder);
}
@Override
public HolderEnum holderType() {
return HolderEnum.TABLE;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java | package com.alibaba.excel.write.metadata.holder;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.enums.WriteLastRowTypeEnum;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
/**
* sheet holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class WriteSheetHolder extends AbstractWriteHolder {
/**
* current param
*/
private WriteSheet writeSheet;
/***
* Current poi Sheet.This is only for writing, and there may be no data in version 07 when template data needs to be
* read.
* <ul>
* <li>03:{@link HSSFSheet}</li>
* <li>07:{@link SXSSFSheet}</li>
* </ul>
*/
private Sheet sheet;
/***
* Current poi Sheet.Be sure to use and this method when reading template data.
* <ul>
* <li>03:{@link HSSFSheet}</li>
* <li>07:{@link XSSFSheet}</li>
* </ul>
*/
private Sheet cachedSheet;
/***
* sheetNo
*/
private Integer sheetNo;
/***
* sheetName
*/
private String sheetName;
/***
* poi sheet
*/
private WriteWorkbookHolder parentWriteWorkbookHolder;
/***
* has been initialized table
*/
private Map<Integer, WriteTableHolder> hasBeenInitializedTable;
/**
* last column type
*
* @param writeSheet
* @param writeWorkbookHolder
*/
private WriteLastRowTypeEnum writeLastRowTypeEnum;
/**
* last row index
*/
private Integer lastRowIndex;
public WriteSheetHolder(WriteSheet writeSheet, WriteWorkbookHolder writeWorkbookHolder) {
super(writeSheet, writeWorkbookHolder);
// init handler
initHandler(writeSheet, writeWorkbookHolder);
this.writeSheet = writeSheet;
if (writeSheet.getSheetNo() == null && StringUtils.isEmpty(writeSheet.getSheetName())) {
this.sheetNo = 0;
} else {
this.sheetNo = writeSheet.getSheetNo();
}
this.sheetName = writeSheet.getSheetName();
this.parentWriteWorkbookHolder = writeWorkbookHolder;
this.hasBeenInitializedTable = new HashMap<>();
if (writeWorkbookHolder.getTempTemplateInputStream() != null) {
writeLastRowTypeEnum = WriteLastRowTypeEnum.TEMPLATE_EMPTY;
} else {
writeLastRowTypeEnum = WriteLastRowTypeEnum.COMMON_EMPTY;
}
lastRowIndex = 0;
}
/**
* Get the last line of index, you have to make sure that the data is written next
*
* @return
*/
public int getNewRowIndexAndStartDoWrite() {
// 'getLastRowNum' doesn't matter if it has one or zero, it's zero
int newRowIndex = 0;
switch (writeLastRowTypeEnum) {
case TEMPLATE_EMPTY:
newRowIndex = Math.max(sheet.getLastRowNum(), cachedSheet.getLastRowNum());
if (newRowIndex != 0 || cachedSheet.getRow(0) != null) {
newRowIndex++;
}
break;
case HAS_DATA:
newRowIndex = Math.max(sheet.getLastRowNum(), cachedSheet.getLastRowNum());
newRowIndex++;
break;
default:
break;
}
writeLastRowTypeEnum = WriteLastRowTypeEnum.HAS_DATA;
return newRowIndex;
}
@Override
public HolderEnum holderType() {
return HolderEnum.SHEET;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java | package com.alibaba.excel.write.metadata.holder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.converters.DefaultConverterLoader;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.metadata.AbstractHolder;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.metadata.property.LoopMergeProperty;
import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty;
import com.alibaba.excel.metadata.property.RowHeightProperty;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.DefaultWriteHandlerLoader;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.handler.chain.CellHandlerExecutionChain;
import com.alibaba.excel.write.handler.chain.RowHandlerExecutionChain;
import com.alibaba.excel.write.handler.chain.SheetHandlerExecutionChain;
import com.alibaba.excel.write.handler.chain.WorkbookHandlerExecutionChain;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.WriteBasicParameter;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
/**
* Write holder configuration
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public abstract class AbstractWriteHolder extends AbstractHolder implements WriteHolder {
/**
* Need Head
*/
private Boolean needHead;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer relativeHeadRowIndex;
/**
* Excel head property
*/
private ExcelWriteHeadProperty excelWriteHeadProperty;
/**
* Use the default style.Default is true.
*/
private Boolean useDefaultStyle;
/**
* Whether to automatically merge headers.Default is true.
*/
private Boolean automaticMergeHead;
/**
* Ignore the custom columns.
*/
private Collection<Integer> excludeColumnIndexes;
/**
* Ignore the custom columns.
*/
private Collection<String> excludeColumnFieldNames;
/**
* Only output the custom columns.
*/
private Collection<Integer> includeColumnIndexes;
/**
* Only output the custom columns.
*/
private Collection<String> includeColumnFieldNames;
/**
* Data will be order by {@link #includeColumnFieldNames} or {@link #includeColumnIndexes}.
*
* default is false.
*/
private Boolean orderByIncludeColumn;
/**
* Write handler
*/
private List<WriteHandler> writeHandlerList;
/**
* Execute the workbook handler chain
* Created in the sheet in the workbook interceptors will not be executed because the workbook to
* create an event long past. So when initializing sheet, supplementary workbook event.
*/
public WorkbookHandlerExecutionChain ownWorkbookHandlerExecutionChain;
/**
* Execute the sheet handler chain
* Created in the sheet in the workbook interceptors will not be executed because the workbook to
* create an event long past. So when initializing sheet, supplementary workbook event.
*/
public SheetHandlerExecutionChain ownSheetHandlerExecutionChain;
/**
* Execute the workbook handler chain
*/
public WorkbookHandlerExecutionChain workbookHandlerExecutionChain;
/**
* Execute the sheet handler chain
*/
public SheetHandlerExecutionChain sheetHandlerExecutionChain;
/**
* Execute the row handler chain
*/
public RowHandlerExecutionChain rowHandlerExecutionChain;
/**
* Execute the cell handler chain
*/
public CellHandlerExecutionChain cellHandlerExecutionChain;
public AbstractWriteHolder(WriteBasicParameter writeBasicParameter, AbstractWriteHolder parentAbstractWriteHolder) {
super(writeBasicParameter, parentAbstractWriteHolder);
if (writeBasicParameter.getUseScientificFormat() != null) {
throw new UnsupportedOperationException("Currently does not support setting useScientificFormat.");
}
if (writeBasicParameter.getNeedHead() == null) {
if (parentAbstractWriteHolder == null) {
this.needHead = Boolean.TRUE;
} else {
this.needHead = parentAbstractWriteHolder.getNeedHead();
}
} else {
this.needHead = writeBasicParameter.getNeedHead();
}
if (writeBasicParameter.getRelativeHeadRowIndex() == null) {
if (parentAbstractWriteHolder == null) {
this.relativeHeadRowIndex = 0;
} else {
this.relativeHeadRowIndex = parentAbstractWriteHolder.getRelativeHeadRowIndex();
}
} else {
this.relativeHeadRowIndex = writeBasicParameter.getRelativeHeadRowIndex();
}
if (writeBasicParameter.getUseDefaultStyle() == null) {
if (parentAbstractWriteHolder == null) {
this.useDefaultStyle = Boolean.TRUE;
} else {
this.useDefaultStyle = parentAbstractWriteHolder.getUseDefaultStyle();
}
} else {
this.useDefaultStyle = writeBasicParameter.getUseDefaultStyle();
}
if (writeBasicParameter.getAutomaticMergeHead() == null) {
if (parentAbstractWriteHolder == null) {
this.automaticMergeHead = Boolean.TRUE;
} else {
this.automaticMergeHead = parentAbstractWriteHolder.getAutomaticMergeHead();
}
} else {
this.automaticMergeHead = writeBasicParameter.getAutomaticMergeHead();
}
if (writeBasicParameter.getExcludeColumnFieldNames() == null && parentAbstractWriteHolder != null) {
this.excludeColumnFieldNames = parentAbstractWriteHolder.getExcludeColumnFieldNames();
} else {
this.excludeColumnFieldNames = writeBasicParameter.getExcludeColumnFieldNames();
}
if (writeBasicParameter.getExcludeColumnIndexes() == null && parentAbstractWriteHolder != null) {
this.excludeColumnIndexes = parentAbstractWriteHolder.getExcludeColumnIndexes();
} else {
this.excludeColumnIndexes = writeBasicParameter.getExcludeColumnIndexes();
}
if (writeBasicParameter.getIncludeColumnFieldNames() == null && parentAbstractWriteHolder != null) {
this.includeColumnFieldNames = parentAbstractWriteHolder.getIncludeColumnFieldNames();
} else {
this.includeColumnFieldNames = writeBasicParameter.getIncludeColumnFieldNames();
}
if (writeBasicParameter.getOrderByIncludeColumn() == null) {
if (parentAbstractWriteHolder == null) {
this.orderByIncludeColumn = Boolean.FALSE;
} else {
this.orderByIncludeColumn = parentAbstractWriteHolder.getOrderByIncludeColumn();
}
} else {
this.orderByIncludeColumn = writeBasicParameter.getOrderByIncludeColumn();
}
if (writeBasicParameter.getIncludeColumnIndexes() == null && parentAbstractWriteHolder != null) {
this.includeColumnIndexes = parentAbstractWriteHolder.getIncludeColumnIndexes();
} else {
this.includeColumnIndexes = writeBasicParameter.getIncludeColumnIndexes();
}
// Initialization property
this.excelWriteHeadProperty = new ExcelWriteHeadProperty(this, getClazz(), getHead());
// Set converterMap
if (parentAbstractWriteHolder == null) {
setConverterMap(DefaultConverterLoader.loadDefaultWriteConverter());
} else {
setConverterMap(new HashMap<>(parentAbstractWriteHolder.getConverterMap()));
}
if (writeBasicParameter.getCustomConverterList() != null
&& !writeBasicParameter.getCustomConverterList().isEmpty()) {
for (Converter<?> converter : writeBasicParameter.getCustomConverterList()) {
getConverterMap().put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()), converter);
}
}
}
protected void initHandler(WriteBasicParameter writeBasicParameter, AbstractWriteHolder parentAbstractWriteHolder) {
// Set writeHandlerMap
List<WriteHandler> handlerList = new ArrayList<>();
// Initialization Annotation
initAnnotationConfig(handlerList, writeBasicParameter);
if (writeBasicParameter.getCustomWriteHandlerList() != null
&& !writeBasicParameter.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(writeBasicParameter.getCustomWriteHandlerList());
}
sortAndClearUpHandler(handlerList, true);
if (parentAbstractWriteHolder != null) {
if (CollectionUtils.isNotEmpty(parentAbstractWriteHolder.getWriteHandlerList())) {
handlerList.addAll(parentAbstractWriteHolder.getWriteHandlerList());
}
} else {
if (this instanceof WriteWorkbookHolder) {
handlerList.addAll(DefaultWriteHandlerLoader.loadDefaultHandler(useDefaultStyle,
((WriteWorkbookHolder)this).getExcelType()));
}
}
sortAndClearUpHandler(handlerList, false);
}
protected void initAnnotationConfig(List<WriteHandler> handlerList, WriteBasicParameter writeBasicParameter) {
if (!HeadKindEnum.CLASS.equals(getExcelWriteHeadProperty().getHeadKind())) {
return;
}
if (writeBasicParameter.getClazz() == null) {
return;
}
Map<Integer, Head> headMap = getExcelWriteHeadProperty().getHeadMap();
boolean hasColumnWidth = false;
for (Head head : headMap.values()) {
if (head.getColumnWidthProperty() != null) {
hasColumnWidth = true;
}
dealLoopMerge(handlerList, head);
}
if (hasColumnWidth) {
dealColumnWidth(handlerList);
}
dealStyle(handlerList);
dealRowHigh(handlerList);
dealOnceAbsoluteMerge(handlerList);
}
private void dealStyle(List<WriteHandler> handlerList) {
WriteHandler styleStrategy = new AbstractVerticalCellStyleStrategy() {
@Override
public int order() {
return OrderConstant.ANNOTATION_DEFINE_STYLE;
}
@Override
protected WriteCellStyle headCellStyle(CellWriteHandlerContext context) {
Head head = context.getHeadData();
if (head == null) {
return null;
}
return WriteCellStyle.build(head.getHeadStyleProperty(), head.getHeadFontProperty());
}
@Override
protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) {
ExcelContentProperty excelContentProperty = context.getExcelContentProperty();
return WriteCellStyle.build(excelContentProperty.getContentStyleProperty(),
excelContentProperty.getContentFontProperty());
}
};
handlerList.add(styleStrategy);
}
private void dealLoopMerge(List<WriteHandler> handlerList, Head head) {
LoopMergeProperty loopMergeProperty = head.getLoopMergeProperty();
if (loopMergeProperty == null) {
return;
}
handlerList.add(new LoopMergeStrategy(loopMergeProperty, head.getColumnIndex()));
}
private void dealOnceAbsoluteMerge(List<WriteHandler> handlerList) {
OnceAbsoluteMergeProperty onceAbsoluteMergeProperty =
getExcelWriteHeadProperty().getOnceAbsoluteMergeProperty();
if (onceAbsoluteMergeProperty == null) {
return;
}
handlerList.add(new OnceAbsoluteMergeStrategy(onceAbsoluteMergeProperty));
}
private void dealRowHigh(List<WriteHandler> handlerList) {
RowHeightProperty headRowHeightProperty = getExcelWriteHeadProperty().getHeadRowHeightProperty();
RowHeightProperty contentRowHeightProperty = getExcelWriteHeadProperty().getContentRowHeightProperty();
if (headRowHeightProperty == null && contentRowHeightProperty == null) {
return;
}
Short headRowHeight = null;
if (headRowHeightProperty != null) {
headRowHeight = headRowHeightProperty.getHeight();
}
Short contentRowHeight = null;
if (contentRowHeightProperty != null) {
contentRowHeight = contentRowHeightProperty.getHeight();
}
handlerList.add(new SimpleRowHeightStyleStrategy(headRowHeight, contentRowHeight));
}
private void dealColumnWidth(List<WriteHandler> handlerList) {
WriteHandler columnWidthStyleStrategy = new AbstractHeadColumnWidthStyleStrategy() {
@Override
protected Integer columnWidth(Head head, Integer columnIndex) {
if (head == null) {
return null;
}
if (head.getColumnWidthProperty() != null) {
return head.getColumnWidthProperty().getWidth();
}
return null;
}
};
handlerList.add(columnWidthStyleStrategy);
}
protected void sortAndClearUpHandler(List<WriteHandler> handlerList, boolean runOwn) {
// sort
Map<Integer, List<WriteHandler>> orderExcelWriteHandlerMap = new TreeMap<>();
for (WriteHandler handler : handlerList) {
int order = handler.order();
if (orderExcelWriteHandlerMap.containsKey(order)) {
orderExcelWriteHandlerMap.get(order).add(handler);
} else {
List<WriteHandler> tempHandlerList = new ArrayList<>();
tempHandlerList.add(handler);
orderExcelWriteHandlerMap.put(order, tempHandlerList);
}
}
// clean up
Set<String> alreadyExistedHandlerSet = new HashSet<>();
List<WriteHandler> cleanUpHandlerList = new ArrayList<>();
for (Map.Entry<Integer, List<WriteHandler>> entry : orderExcelWriteHandlerMap.entrySet()) {
for (WriteHandler handler : entry.getValue()) {
if (handler instanceof NotRepeatExecutor) {
String uniqueValue = ((NotRepeatExecutor)handler).uniqueValue();
if (alreadyExistedHandlerSet.contains(uniqueValue)) {
continue;
}
alreadyExistedHandlerSet.add(uniqueValue);
}
cleanUpHandlerList.add(handler);
}
}
// build chain
if (!runOwn) {
this.writeHandlerList = new ArrayList<>();
}
for (WriteHandler writeHandler : cleanUpHandlerList) {
buildChain(writeHandler, runOwn);
}
}
protected void buildChain(WriteHandler writeHandler, boolean runOwn) {
if (writeHandler instanceof CellWriteHandler) {
if (!runOwn) {
if (cellHandlerExecutionChain == null) {
cellHandlerExecutionChain = new CellHandlerExecutionChain((CellWriteHandler)writeHandler);
} else {
cellHandlerExecutionChain.addLast((CellWriteHandler)writeHandler);
}
}
}
if (writeHandler instanceof RowWriteHandler) {
if (!runOwn) {
if (rowHandlerExecutionChain == null) {
rowHandlerExecutionChain = new RowHandlerExecutionChain((RowWriteHandler)writeHandler);
} else {
rowHandlerExecutionChain.addLast((RowWriteHandler)writeHandler);
}
}
}
if (writeHandler instanceof SheetWriteHandler) {
if (!runOwn) {
if (sheetHandlerExecutionChain == null) {
sheetHandlerExecutionChain = new SheetHandlerExecutionChain((SheetWriteHandler)writeHandler);
} else {
sheetHandlerExecutionChain.addLast((SheetWriteHandler)writeHandler);
}
} else {
if (ownSheetHandlerExecutionChain == null) {
ownSheetHandlerExecutionChain = new SheetHandlerExecutionChain((SheetWriteHandler)writeHandler);
} else {
ownSheetHandlerExecutionChain.addLast((SheetWriteHandler)writeHandler);
}
}
}
if (writeHandler instanceof WorkbookWriteHandler) {
if (!runOwn) {
if (workbookHandlerExecutionChain == null) {
workbookHandlerExecutionChain = new WorkbookHandlerExecutionChain(
(WorkbookWriteHandler)writeHandler);
} else {
workbookHandlerExecutionChain.addLast((WorkbookWriteHandler)writeHandler);
}
} else {
if (ownWorkbookHandlerExecutionChain == null) {
ownWorkbookHandlerExecutionChain = new WorkbookHandlerExecutionChain(
(WorkbookWriteHandler)writeHandler);
} else {
ownWorkbookHandlerExecutionChain.addLast((WorkbookWriteHandler)writeHandler);
}
}
}
if (!runOwn) {
this.writeHandlerList.add(writeHandler);
}
}
@Override
public boolean ignore(String fieldName, Integer columnIndex) {
if (fieldName != null) {
if (includeColumnFieldNames != null && !includeColumnFieldNames.contains(fieldName)) {
return true;
}
if (excludeColumnFieldNames != null && excludeColumnFieldNames.contains(fieldName)) {
return true;
}
}
if (columnIndex != null) {
if (includeColumnIndexes != null && !includeColumnIndexes.contains(columnIndex)) {
return true;
}
if (excludeColumnIndexes != null && excludeColumnIndexes.contains(columnIndex)) {
return true;
}
}
return false;
}
@Override
public ExcelWriteHeadProperty excelWriteHeadProperty() {
return getExcelWriteHeadProperty();
}
@Override
public boolean needHead() {
return getNeedHead();
}
@Override
public int relativeHeadRowIndex() {
return getRelativeHeadRowIndex();
}
@Override
public boolean automaticMergeHead() {
return getAutomaticMergeHead();
}
@Override
public boolean orderByIncludeColumn() {
return getOrderByIncludeColumn();
}
@Override
public Collection<Integer> includeColumnIndexes() {
return getIncludeColumnIndexes();
}
@Override
public Collection<String> includeColumnFieldNames() {
return getIncludeColumnFieldNames();
}
@Override
public Collection<Integer> excludeColumnIndexes() {
return getExcludeColumnIndexes();
}
@Override
public Collection<String> excludeColumnFieldNames() {
return getExcludeColumnFieldNames();
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java | package com.alibaba.excel.write.metadata.holder;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.excel.enums.CacheLocationEnum;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.IoUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString.Exclude;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Workbook holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@Slf4j
public class WriteWorkbookHolder extends AbstractWriteHolder {
/***
* Current poi Workbook.This is only for writing, and there may be no data in version 07 when template data needs to
* be read.
* <ul>
* <li>03:{@link HSSFWorkbook}</li>
* <li>07:{@link SXSSFWorkbook}</li>
* </ul>
*/
private Workbook workbook;
/***
* Current poi Workbook.Be sure to use and this method when reading template data.
* <ul>
* <li>03:{@link HSSFWorkbook}</li>
* <li>07:{@link XSSFWorkbook}</li>
* </ul>
*/
private Workbook cachedWorkbook;
/**
* current param
*/
private WriteWorkbook writeWorkbook;
/**
* Final output file
* <p>
* If 'outputStream' and 'file' all not empty, file first
*/
private File file;
/**
* Final output stream
*/
private OutputStream outputStream;
/**
* charset.
* Only work on the CSV file
*/
private Charset charset;
/**
* Set the encoding prefix in the csv file, otherwise the office may open garbled characters.
* Default true.
*/
private Boolean withBom;
/**
* Template input stream
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private InputStream templateInputStream;
/**
* Template file
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private File templateFile;
/**
* Temporary template file stream.
* <p>
* A temporary file stream needs to be created in order not to modify the original template file.
*/
private InputStream tempTemplateInputStream;
/**
* Default true
*/
private Boolean autoCloseStream;
/**
* Excel type
*/
private ExcelTypeEnum excelType;
/**
* Mandatory use 'inputStream'
*/
private Boolean mandatoryUseInputStream;
/**
* prevent duplicate creation of sheet objects
*/
private Map<Integer, WriteSheetHolder> hasBeenInitializedSheetIndexMap;
/**
* prevent duplicate creation of sheet objects
*/
private Map<String, WriteSheetHolder> hasBeenInitializedSheetNameMap;
/**
* Whether the encryption
*/
private String password;
/**
* Write excel in memory. Default false, the cache file is created and finally written to excel.
* <p>
* Comment and RichTextString are only supported in memory mode.
*/
private Boolean inMemory;
/**
* Excel is also written in the event of an exception being thrown.The default false.
*/
private Boolean writeExcelOnException;
/**
* Used to cell style.
*/
private Map<Short, Map<WriteCellStyle, CellStyle>> cellStyleIndexMap;
/**
* Used to font.
*/
private Map<WriteFont, Font> fontMap;
/**
* Used to data format.
*/
private Map<DataFormatData, Short> dataFormatMap;
/**
* handler context
*/
@Exclude
private WorkbookWriteHandlerContext workbookWriteHandlerContext;
public WriteWorkbookHolder(WriteWorkbook writeWorkbook) {
super(writeWorkbook, null);
this.writeWorkbook = writeWorkbook;
this.file = writeWorkbook.getFile();
if (file != null) {
try {
this.outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not found file.", e);
}
} else {
this.outputStream = writeWorkbook.getOutputStream();
}
if (writeWorkbook.getCharset() == null) {
this.charset = Charset.defaultCharset();
} else {
this.charset = writeWorkbook.getCharset();
}
if (writeWorkbook.getWithBom() == null) {
this.withBom = Boolean.TRUE;
} else {
this.withBom = writeWorkbook.getWithBom();
}
if (writeWorkbook.getAutoCloseStream() == null) {
this.autoCloseStream = Boolean.TRUE;
} else {
this.autoCloseStream = writeWorkbook.getAutoCloseStream();
}
if (writeWorkbook.getExcelType() == null) {
boolean isXls = (file != null && file.getName().endsWith(ExcelTypeEnum.XLS.getValue()))
|| (writeWorkbook.getTemplateFile() != null
&& writeWorkbook.getTemplateFile().getName().endsWith(ExcelTypeEnum.XLS.getValue()));
if (isXls) {
this.excelType = ExcelTypeEnum.XLS;
} else {
boolean isCsv = (file != null && file.getName().endsWith(ExcelTypeEnum.CSV.getValue()))
|| (writeWorkbook.getTemplateFile() != null
&& writeWorkbook.getTemplateFile().getName().endsWith(ExcelTypeEnum.CSV.getValue()));
if (isCsv) {
this.excelType = ExcelTypeEnum.CSV;
} else {
this.excelType = ExcelTypeEnum.XLSX;
}
}
} else {
this.excelType = writeWorkbook.getExcelType();
}
// init handler
initHandler(writeWorkbook, null);
try {
copyTemplate();
} catch (IOException e) {
throw new ExcelGenerateException("Copy template failure.", e);
}
if (writeWorkbook.getMandatoryUseInputStream() == null) {
this.mandatoryUseInputStream = Boolean.FALSE;
} else {
this.mandatoryUseInputStream = writeWorkbook.getMandatoryUseInputStream();
}
this.hasBeenInitializedSheetIndexMap = new HashMap<>();
this.hasBeenInitializedSheetNameMap = new HashMap<>();
this.password = writeWorkbook.getPassword();
if (writeWorkbook.getInMemory() == null) {
this.inMemory = Boolean.FALSE;
} else {
this.inMemory = writeWorkbook.getInMemory();
}
if (writeWorkbook.getWriteExcelOnException() == null) {
this.writeExcelOnException = Boolean.FALSE;
} else {
this.writeExcelOnException = writeWorkbook.getWriteExcelOnException();
}
this.cellStyleIndexMap = MapUtils.newHashMap();
this.fontMap = MapUtils.newHashMap();
this.dataFormatMap = MapUtils.newHashMap();
}
private void copyTemplate() throws IOException {
if (writeWorkbook.getTemplateFile() == null && writeWorkbook.getTemplateInputStream() == null) {
return;
}
if (this.excelType == ExcelTypeEnum.CSV) {
throw new ExcelGenerateException("csv cannot use template.");
}
byte[] templateFileByte = null;
if (writeWorkbook.getTemplateFile() != null) {
templateFileByte = FileUtils.readFileToByteArray(writeWorkbook.getTemplateFile());
} else if (writeWorkbook.getTemplateInputStream() != null) {
try {
templateFileByte = IoUtils.toByteArray(writeWorkbook.getTemplateInputStream());
} finally {
if (autoCloseStream) {
writeWorkbook.getTemplateInputStream().close();
}
}
}
this.tempTemplateInputStream = new ByteArrayInputStream(templateFileByte);
}
@Override
public HolderEnum holderType() {
return HolderEnum.WORKBOOK;
}
/**
* create a cell style.
*
* @param writeCellStyle
* @param originCellStyle
* @return
*/
public CellStyle createCellStyle(WriteCellStyle writeCellStyle, CellStyle originCellStyle) {
if (writeCellStyle == null) {
return originCellStyle;
}
short styleIndex = -1;
Font originFont = null;
boolean useCache = true;
if (originCellStyle != null) {
styleIndex = originCellStyle.getIndex();
if (originCellStyle instanceof XSSFCellStyle) {
originFont = ((XSSFCellStyle)originCellStyle).getFont();
} else if (originCellStyle instanceof HSSFCellStyle) {
originFont = ((HSSFCellStyle)originCellStyle).getFont(workbook);
}
useCache = false;
}
Map<WriteCellStyle, CellStyle> cellStyleMap = cellStyleIndexMap.computeIfAbsent(styleIndex,
key -> MapUtils.newHashMap());
CellStyle cellStyle = cellStyleMap.get(writeCellStyle);
if (cellStyle != null) {
return cellStyle;
}
if (log.isDebugEnabled()) {
log.info("create new style:{},{}", writeCellStyle, originCellStyle);
}
WriteCellStyle tempWriteCellStyle = new WriteCellStyle();
WriteCellStyle.merge(writeCellStyle, tempWriteCellStyle);
cellStyle = StyleUtil.buildCellStyle(workbook, originCellStyle, tempWriteCellStyle);
Short dataFormat = createDataFormat(tempWriteCellStyle.getDataFormatData(), useCache);
if (dataFormat != null) {
cellStyle.setDataFormat(dataFormat);
}
Font font = createFont(tempWriteCellStyle.getWriteFont(), originFont, useCache);
if (font != null) {
cellStyle.setFont(font);
}
cellStyleMap.put(tempWriteCellStyle, cellStyle);
return cellStyle;
}
/**
* create a font.
*
* @param writeFont
* @param originFont
* @param useCache
* @return
*/
public Font createFont(WriteFont writeFont, Font originFont, boolean useCache) {
if (!useCache) {
return StyleUtil.buildFont(workbook, originFont, writeFont);
}
WriteFont tempWriteFont = new WriteFont();
WriteFont.merge(writeFont, tempWriteFont);
Font font = fontMap.get(tempWriteFont);
if (font != null) {
return font;
}
font = StyleUtil.buildFont(workbook, originFont, tempWriteFont);
fontMap.put(tempWriteFont, font);
return font;
}
/**
* create a data format.
*
* @param dataFormatData
* @param useCache
* @return
*/
public Short createDataFormat(DataFormatData dataFormatData, boolean useCache) {
if (dataFormatData == null) {
return null;
}
if (!useCache) {
return StyleUtil.buildDataFormat(workbook, dataFormatData);
}
DataFormatData tempDataFormatData = new DataFormatData();
DataFormatData.merge(dataFormatData, tempDataFormatData);
Short dataFormat = dataFormatMap.get(tempDataFormatData);
if (dataFormat != null) {
return dataFormat;
}
dataFormat = StyleUtil.buildDataFormat(workbook, tempDataFormatData);
dataFormatMap.put(tempDataFormatData, dataFormat);
return dataFormat;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteHolder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/metadata/holder/WriteHolder.java | package com.alibaba.excel.write.metadata.holder;
import java.util.Collection;
import com.alibaba.excel.metadata.ConfigurationHolder;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
/**
* Get the corresponding Holder
*
* @author Jiaju Zhuang
**/
public interface WriteHolder extends ConfigurationHolder {
/**
* What 'ExcelWriteHeadProperty' does the currently operated cell need to execute
*
* @return
*/
ExcelWriteHeadProperty excelWriteHeadProperty();
/**
* Is to determine if a field needs to be ignored
*
* @param fieldName
* @param columnIndex
* @return
*/
boolean ignore(String fieldName, Integer columnIndex);
/**
* Whether a header is required for the currently operated cell
*
* @return
*/
boolean needHead();
/**
* Whether need automatic merge headers.
*
* @return
*/
boolean automaticMergeHead();
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @return
*/
int relativeHeadRowIndex();
/**
* Data will be order by {@link #includeColumnFieldNames} or {@link #includeColumnIndexes}.
*
* default is false.
*
* @return
*/
boolean orderByIncludeColumn();
/**
* Only output the custom columns.
*
* @return
*/
Collection<Integer> includeColumnIndexes();
/**
* Only output the custom columns.
*
* @return
*/
Collection<String> includeColumnFieldNames();
/**
* Ignore the custom columns.
*
* @return
*/
Collection<Integer> excludeColumnIndexes();
/**
* Ignore the custom columns.
*
* @return
*/
Collection<String> excludeColumnFieldNames();
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java | package com.alibaba.excel.write.builder;
import java.util.Collection;
import java.util.function.Supplier;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
/**
* Build sheet
*
* @author Jiaju Zhuang
*/
public class ExcelWriterTableBuilder extends AbstractExcelWriterParameterBuilder<ExcelWriterTableBuilder, WriteTable> {
private ExcelWriter excelWriter;
private WriteSheet writeSheet;
/**
* table
*/
private final WriteTable writeTable;
public ExcelWriterTableBuilder() {
this.writeTable = new WriteTable();
}
public ExcelWriterTableBuilder(ExcelWriter excelWriter, WriteSheet writeSheet) {
this.excelWriter = excelWriter;
this.writeSheet = writeSheet;
this.writeTable = new WriteTable();
}
/**
* Starting from 0
*
* @param tableNo
* @return
*/
public ExcelWriterTableBuilder tableNo(Integer tableNo) {
writeTable.setTableNo(tableNo);
return this;
}
public WriteTable build() {
return writeTable;
}
public void doWrite(Collection<?> data) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet().table()' to call this method");
}
excelWriter.write(data, writeSheet, build());
excelWriter.finish();
}
public void doWrite(Supplier<Collection<?>> supplier) {
doWrite(supplier.get());
}
@Override
protected WriteTable parameter() {
return writeTable;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java | package com.alibaba.excel.write.builder;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteWorkbook;
/**
* Build ExcelBuilder
*
* @author Jiaju Zhuang
*/
public class ExcelWriterBuilder extends AbstractExcelWriterParameterBuilder<ExcelWriterBuilder, WriteWorkbook> {
/**
* Workbook
*/
private final WriteWorkbook writeWorkbook;
public ExcelWriterBuilder() {
this.writeWorkbook = new WriteWorkbook();
}
/**
* Default true
*
* @param autoCloseStream
* @return
*/
public ExcelWriterBuilder autoCloseStream(Boolean autoCloseStream) {
writeWorkbook.setAutoCloseStream(autoCloseStream);
return this;
}
/**
* Whether the encryption.
* <p>
* WARRING:Encryption is when the entire file is read into memory, so it is very memory intensive.
*
* @param password
* @return
*/
public ExcelWriterBuilder password(String password) {
writeWorkbook.setPassword(password);
return this;
}
/**
* Write excel in memory. Default false, the cache file is created and finally written to excel.
* <p>
* Comment and RichTextString are only supported in memory mode.
*/
public ExcelWriterBuilder inMemory(Boolean inMemory) {
writeWorkbook.setInMemory(inMemory);
return this;
}
/**
* Excel is also written in the event of an exception being thrown.The default false.
*/
public ExcelWriterBuilder writeExcelOnException(Boolean writeExcelOnException) {
writeWorkbook.setWriteExcelOnException(writeExcelOnException);
return this;
}
public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) {
writeWorkbook.setExcelType(excelType);
return this;
}
public ExcelWriterBuilder file(OutputStream outputStream) {
writeWorkbook.setOutputStream(outputStream);
return this;
}
public ExcelWriterBuilder file(File outputFile) {
writeWorkbook.setFile(outputFile);
return this;
}
public ExcelWriterBuilder file(String outputPathName) {
return file(new File(outputPathName));
}
/**
* charset.
* Only work on the CSV file
*/
public ExcelWriterBuilder charset(Charset charset) {
writeWorkbook.setCharset(charset);
return this;
}
/**
* Set the encoding prefix in the csv file, otherwise the office may open garbled characters.
* Default true.
*/
public ExcelWriterBuilder withBom(Boolean withBom) {
writeWorkbook.setWithBom(withBom);
return this;
}
/**
* Template file.
* This file is read into memory, excessive cases can lead to OOM.
*/
public ExcelWriterBuilder withTemplate(InputStream templateInputStream) {
writeWorkbook.setTemplateInputStream(templateInputStream);
return this;
}
/**
* Template file.
* This file is read into memory, excessive cases can lead to OOM.
*/
public ExcelWriterBuilder withTemplate(File templateFile) {
writeWorkbook.setTemplateFile(templateFile);
return this;
}
/**
* Template file.
* This file is read into memory, excessive cases can lead to OOM.
*/
public ExcelWriterBuilder withTemplate(String pathName) {
return withTemplate(new File(pathName));
}
public ExcelWriter build() {
return new ExcelWriter(writeWorkbook);
}
public ExcelWriterSheetBuilder sheet() {
return sheet(null, null);
}
public ExcelWriterSheetBuilder sheet(Integer sheetNo) {
return sheet(sheetNo, null);
}
public ExcelWriterSheetBuilder sheet(String sheetName) {
return sheet(null, sheetName);
}
public ExcelWriterSheetBuilder sheet(Integer sheetNo, String sheetName) {
ExcelWriter excelWriter = build();
ExcelWriterSheetBuilder excelWriterSheetBuilder = new ExcelWriterSheetBuilder(excelWriter);
if (sheetNo != null) {
excelWriterSheetBuilder.sheetNo(sheetNo);
}
if (sheetName != null) {
excelWriterSheetBuilder.sheetName(sheetName);
}
return excelWriterSheetBuilder;
}
@Override
protected WriteWorkbook parameter() {
return writeWorkbook;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java | package com.alibaba.excel.write.builder;
import java.util.Collection;
import java.util.function.Supplier;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
/**
* Build sheet
*
* @author Jiaju Zhuang
*/
public class ExcelWriterSheetBuilder extends AbstractExcelWriterParameterBuilder<ExcelWriterSheetBuilder, WriteSheet> {
private ExcelWriter excelWriter;
/**
* Sheet
*/
private final WriteSheet writeSheet;
public ExcelWriterSheetBuilder() {
this.writeSheet = new WriteSheet();
}
public ExcelWriterSheetBuilder(ExcelWriter excelWriter) {
this.writeSheet = new WriteSheet();
this.excelWriter = excelWriter;
}
/**
* Starting from 0
*
* @param sheetNo
* @return
*/
public ExcelWriterSheetBuilder sheetNo(Integer sheetNo) {
writeSheet.setSheetNo(sheetNo);
return this;
}
/**
* sheet name
*
* @param sheetName
* @return
*/
public ExcelWriterSheetBuilder sheetName(String sheetName) {
writeSheet.setSheetName(sheetName);
return this;
}
public WriteSheet build() {
return writeSheet;
}
public void doWrite(Collection<?> data) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method");
}
excelWriter.write(data, build());
excelWriter.finish();
}
public void doFill(Object data) {
doFill(data, null);
}
public void doFill(Object data, FillConfig fillConfig) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method");
}
excelWriter.fill(data, fillConfig, build());
excelWriter.finish();
}
public void doWrite(Supplier<Collection<?>> supplier) {
doWrite(supplier.get());
}
public void doFill(Supplier<Object> supplier) {
doFill(supplier.get());
}
public void doFill(Supplier<Object> supplier, FillConfig fillConfig) {
doFill(supplier.get(), fillConfig);
}
public ExcelWriterTableBuilder table() {
return table(null);
}
public ExcelWriterTableBuilder table(Integer tableNo) {
ExcelWriterTableBuilder excelWriterTableBuilder = new ExcelWriterTableBuilder(excelWriter, build());
if (tableNo != null) {
excelWriterTableBuilder.tableNo(tableNo);
}
return excelWriterTableBuilder;
}
@Override
protected WriteSheet parameter() {
return writeSheet;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/builder/AbstractExcelWriterParameterBuilder.java | easyexcel-core/src/main/java/com/alibaba/excel/write/builder/AbstractExcelWriterParameterBuilder.java | package com.alibaba.excel.write.builder;
import java.util.ArrayList;
import java.util.Collection;
import com.alibaba.excel.metadata.AbstractParameterBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteBasicParameter;
/**
* Build ExcelBuilder
*
* @author Jiaju Zhuang
*/
public abstract class AbstractExcelWriterParameterBuilder<T extends AbstractExcelWriterParameterBuilder,
C extends WriteBasicParameter> extends AbstractParameterBuilder<T, C> {
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @param relativeHeadRowIndex
* @return
*/
public T relativeHeadRowIndex(Integer relativeHeadRowIndex) {
parameter().setRelativeHeadRowIndex(relativeHeadRowIndex);
return self();
}
/**
* Need Head
*/
public T needHead(Boolean needHead) {
parameter().setNeedHead(needHead);
return self();
}
/**
* Custom write handler
*
* @param writeHandler
* @return
*/
public T registerWriteHandler(WriteHandler writeHandler) {
if (parameter().getCustomWriteHandlerList() == null) {
parameter().setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
parameter().getCustomWriteHandlerList().add(writeHandler);
return self();
}
/**
* Use the default style.Default is true.
*
* @param useDefaultStyle
* @return
*/
public T useDefaultStyle(Boolean useDefaultStyle) {
parameter().setUseDefaultStyle(useDefaultStyle);
return self();
}
/**
* Whether to automatically merge headers.Default is true.
*
* @param automaticMergeHead
* @return
*/
public T automaticMergeHead(Boolean automaticMergeHead) {
parameter().setAutomaticMergeHead(automaticMergeHead);
return self();
}
/**
* Ignore the custom columns.
*/
public T excludeColumnIndexes(Collection<Integer> excludeColumnIndexes) {
parameter().setExcludeColumnIndexes(excludeColumnIndexes);
return self();
}
/**
* Ignore the custom columns.
*
* @deprecated use {@link #excludeColumnFieldNames(Collection)}
*/
public T excludeColumnFiledNames(Collection<String> excludeColumnFieldNames) {
parameter().setExcludeColumnFieldNames(excludeColumnFieldNames);
return self();
}
/**
* Ignore the custom columns.
*/
public T excludeColumnFieldNames(Collection<String> excludeColumnFieldNames) {
parameter().setExcludeColumnFieldNames(excludeColumnFieldNames);
return self();
}
/**
* Only output the custom columns.
*/
public T includeColumnIndexes(Collection<Integer> includeColumnIndexes) {
parameter().setIncludeColumnIndexes(includeColumnIndexes);
return self();
}
/**
* Only output the custom columns.
*
* @deprecated use {@link #includeColumnFieldNames(Collection)} spelling mistake
*/
@Deprecated
public T includeColumnFiledNames(Collection<String> includeColumnFieldNames) {
parameter().setIncludeColumnFieldNames(includeColumnFieldNames);
return self();
}
/**
* Only output the custom columns.
*/
public T includeColumnFieldNames(Collection<String> includeColumnFieldNames) {
parameter().setIncludeColumnFieldNames(includeColumnFieldNames);
return self();
}
/**
* Data will be order by {@link #includeColumnFieldNames} or {@link #includeColumnIndexes}.
*
* default is false.
*
* @since 3.3.0
**/
public T orderByIncludeColumn(Boolean orderByIncludeColumn) {
parameter().setOrderByIncludeColumn(orderByIncludeColumn);
return self();
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java | package com.alibaba.excel.write.style;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
/**
* Cell style strategy
*
* @author Jiaju Zhuang
*/
public abstract class AbstractCellStyleStrategy implements CellWriteHandler {
@Override
public int order() {
return OrderConstant.DEFINE_STYLE;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (context.getHead() == null) {
return;
}
if (context.getHead()) {
setHeadCellStyle(context);
} else {
setContentCellStyle(context);
}
}
/**
* Sets the cell style of header
*
* @param context
*/
protected void setHeadCellStyle(CellWriteHandlerContext context) {
setHeadCellStyle(context.getCell(), context.getHeadData(), context.getRelativeRowIndex());
}
/**
* Sets the cell style of header
*
* @param cell
* @param head
* @param relativeRowIndex
*/
protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
throw new UnsupportedOperationException("Custom styles must override the setHeadCellStyle method.");
}
/**
* Sets the cell style of content
*
* @param context
*/
protected void setContentCellStyle(CellWriteHandlerContext context) {
setContentCellStyle(context.getCell(), context.getHeadData(), context.getRelativeRowIndex());
}
/**
* Sets the cell style of content
*
* @param cell
* @param head
* @param relativeRowIndex
*/
protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
throw new UnsupportedOperationException("Custom styles must override the setContentCellStyle method.");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/DefaultStyle.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/DefaultStyle.java | package com.alibaba.excel.write.style;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
/**
* The default styles
*
* @author Jiaju Zhuang
*/
public class DefaultStyle extends HorizontalCellStyleStrategy {
@Override
public int order() {
return OrderConstant.DEFAULT_DEFINE_STYLE;
}
public DefaultStyle() {
super();
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setWrapped(true);
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
headWriteCellStyle.setLocked(true);
headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setBorderTop(BorderStyle.THIN);
headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
headWriteCellStyle.setBorderRight(BorderStyle.THIN);
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontName("宋体");
headWriteFont.setFontHeightInPoints((short)14);
headWriteFont.setBold(true);
headWriteCellStyle.setWriteFont(headWriteFont);
setHeadWriteCellStyle(headWriteCellStyle);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java | package com.alibaba.excel.write.style;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
/**
* Use the same style for the column
*
* @author Jiaju Zhuang
*/
public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyleStrategy {
@Override
protected void setHeadCellStyle(CellWriteHandlerContext context) {
if (stopProcessing(context)) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle.merge(headCellStyle(context), cellData.getOrCreateStyle());
}
@Override
protected void setContentCellStyle(CellWriteHandlerContext context) {
if (context.getFirstCellData() == null) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle.merge(contentCellStyle(context), cellData.getOrCreateStyle());
}
/**
* Returns the column width corresponding to each column head
*
* @param context
* @return
*/
protected WriteCellStyle headCellStyle(CellWriteHandlerContext context) {
return headCellStyle(context.getHeadData());
}
/**
* Returns the column width corresponding to each column head
*
* @param head Nullable
* @return
*/
protected WriteCellStyle headCellStyle(Head head) {
return null;
}
/**
* Returns the column width corresponding to each column head.
*
* @param context
* @return
*/
protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) {
return contentCellStyle(context.getHeadData());
}
/**
* Returns the column width corresponding to each column head
*
* @param head Nullable
* @return
*/
protected WriteCellStyle contentCellStyle(Head head) {
return null;
}
protected boolean stopProcessing(CellWriteHandlerContext context) {
if (context.getFirstCellData() == null) {
return true;
}
return context.getHeadData() == null;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java | package com.alibaba.excel.write.style;
import java.util.List;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
/**
* Use the same style for the row
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy {
private WriteCellStyle headWriteCellStyle;
private List<WriteCellStyle> contentWriteCellStyleList;
public HorizontalCellStyleStrategy() {
}
public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle,
List<WriteCellStyle> contentWriteCellStyleList) {
this.headWriteCellStyle = headWriteCellStyle;
this.contentWriteCellStyleList = contentWriteCellStyleList;
}
public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) {
this.headWriteCellStyle = headWriteCellStyle;
if (contentWriteCellStyle != null) {
this.contentWriteCellStyleList = ListUtils.newArrayList(contentWriteCellStyle);
}
}
@Override
protected void setHeadCellStyle(CellWriteHandlerContext context) {
if (stopProcessing(context) || headWriteCellStyle == null) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle.merge(headWriteCellStyle, cellData.getOrCreateStyle());
}
@Override
protected void setContentCellStyle(CellWriteHandlerContext context) {
if (stopProcessing(context) || CollectionUtils.isEmpty(contentWriteCellStyleList)) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
if (context.getRelativeRowIndex() == null || context.getRelativeRowIndex() <= 0) {
WriteCellStyle.merge(contentWriteCellStyleList.get(0), cellData.getOrCreateStyle());
} else {
WriteCellStyle.merge(
contentWriteCellStyleList.get(context.getRelativeRowIndex() % contentWriteCellStyleList.size()),
cellData.getOrCreateStyle());
}
}
protected boolean stopProcessing(CellWriteHandlerContext context) {
return context.getFirstCellData() == null;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/row/SimpleRowHeightStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/row/SimpleRowHeightStyleStrategy.java | package com.alibaba.excel.write.style.row;
import org.apache.poi.ss.usermodel.Row;
/**
* Set the head column high and content column high
*
* @author Jiaju Zhuang
*/
public class SimpleRowHeightStyleStrategy extends AbstractRowHeightStyleStrategy {
private final Short headRowHeight;
private final Short contentRowHeight;
public SimpleRowHeightStyleStrategy(Short headRowHeight, Short contentRowHeight) {
this.headRowHeight = headRowHeight;
this.contentRowHeight = contentRowHeight;
}
@Override
protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
if (headRowHeight != null) {
row.setHeightInPoints(headRowHeight);
}
}
@Override
protected void setContentColumnHeight(Row row, int relativeRowIndex) {
if (contentRowHeight != null) {
row.setHeightInPoints(contentRowHeight);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java | package com.alibaba.excel.write.style.row;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import org.apache.poi.ss.usermodel.Row;
/**
* Set the row height strategy
*
* @author Jiaju Zhuang
*/
public abstract class AbstractRowHeightStyleStrategy implements RowWriteHandler {
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
if (context.getHead() == null) {
return;
}
if (context.getHead()) {
setHeadColumnHeight(context.getRow(), context.getRelativeRowIndex());
} else {
setContentColumnHeight(context.getRow(), context.getRelativeRowIndex());
}
}
/**
* Sets the height of header
*
* @param row
* @param relativeRowIndex
*/
protected abstract void setHeadColumnHeight(Row row, int relativeRowIndex);
/**
* Sets the height of content
*
* @param row
* @param relativeRowIndex
*/
protected abstract void setContentColumnHeight(Row row, int relativeRowIndex);
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java | package com.alibaba.excel.write.style.column;
import java.util.List;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.poi.ss.usermodel.Cell;
/**
* Returns the column width according to each column header
*
* @author Jiaju Zhuang
*/
public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head,
Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = relativeRowIndex != null && (isHead || relativeRowIndex == 0);
if (!needSetWidth) {
return;
}
Integer width = columnWidth(head, cell.getColumnIndex());
if (width != null) {
width = width * 256;
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), width);
}
}
/**
* Returns the column width corresponding to each column head.
*
* <p>
* if return null, ignore
*
* @param head
* Nullable.
* @param columnIndex
* Not null.
* @return
*/
protected abstract Integer columnWidth(Head head, Integer columnIndex);
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java | package com.alibaba.excel.write.style.column;
import java.util.List;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.poi.ss.usermodel.Cell;
/**
* Column width style strategy
*
* @author Jiaju Zhuang
*/
public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandler {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
setColumnWidth(context);
}
/**
* Sets the column width when head create
*
* @param context
*/
protected void setColumnWidth(CellWriteHandlerContext context) {
setColumnWidth(context.getWriteSheetHolder(), context.getCellDataList(), context.getCell(),
context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Sets the column width when head create
*
* @param writeSheetHolder
* @param cellDataList
* @param cell
* @param head
* @param relativeRowIndex
* @param isHead
*/
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {
throw new UnsupportedOperationException("Custom styles must override the setColumnWidth method.");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java | package com.alibaba.excel.write.style.column;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
/**
* Take the width of the longest column as the width.
* <p>
* This is not very useful at the moment, for example if you have Numbers it will cause a newline.And the length is not
* exactly the same as the actual length.
*
* @author Jiaju Zhuang
*/
public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
private static final int MAX_COLUMN_WIDTH = 255;
private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
Head head,
Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
if (!needSetWidth) {
return;
}
Map<Integer, Integer> maxColumnWidthMap = cache.computeIfAbsent(writeSheetHolder.getSheetNo(), key -> new HashMap<>(16));
Integer columnWidth = dataLength(cellDataList, cell, isHead);
if (columnWidth < 0) {
return;
}
if (columnWidth > MAX_COLUMN_WIDTH) {
columnWidth = MAX_COLUMN_WIDTH;
}
Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
}
}
private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
if (isHead) {
return cell.getStringCellValue().getBytes().length;
}
WriteCellData<?> cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return -1;
}
switch (type) {
case STRING:
return cellData.getStringValue().getBytes().length;
case BOOLEAN:
return cellData.getBooleanValue().toString().getBytes().length;
case NUMBER:
return cellData.getNumberValue().toString().getBytes().length;
default:
return -1;
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java | package com.alibaba.excel.write.style.column;
import com.alibaba.excel.metadata.Head;
/**
* All the columns are the same width
*
* @author Jiaju Zhuang
*/
public class SimpleColumnWidthStyleStrategy extends AbstractHeadColumnWidthStyleStrategy {
private final Integer columnWidth;
/**
*
* @param columnWidth
*/
public SimpleColumnWidthStyleStrategy(Integer columnWidth) {
this.columnWidth = columnWidth;
}
@Override
protected Integer columnWidth(Head head, Integer columnIndex) {
return columnWidth;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java | easyexcel-core/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java | package com.alibaba.excel.write.property;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentLoopMerge;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadFontStyle;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.alibaba.excel.annotation.write.style.OnceAbsoluteMerge;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.metadata.CellRange;
import com.alibaba.excel.metadata.ConfigurationHolder;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.Holder;
import com.alibaba.excel.metadata.property.ColumnWidthProperty;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.metadata.property.FontProperty;
import com.alibaba.excel.metadata.property.LoopMergeProperty;
import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty;
import com.alibaba.excel.metadata.property.RowHeightProperty;
import com.alibaba.excel.metadata.property.StyleProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Define the header attribute of excel
*
* @author jipengfei
*/
@Getter
@Setter
@EqualsAndHashCode
public class ExcelWriteHeadProperty extends ExcelHeadProperty {
private RowHeightProperty headRowHeightProperty;
private RowHeightProperty contentRowHeightProperty;
private OnceAbsoluteMergeProperty onceAbsoluteMergeProperty;
public ExcelWriteHeadProperty(ConfigurationHolder configurationHolder, Class<?> headClazz, List<List<String>> head) {
super(configurationHolder, headClazz, head);
if (getHeadKind() != HeadKindEnum.CLASS) {
return;
}
this.headRowHeightProperty =
RowHeightProperty.build(headClazz.getAnnotation(HeadRowHeight.class));
this.contentRowHeightProperty =
RowHeightProperty.build(headClazz.getAnnotation(ContentRowHeight.class));
this.onceAbsoluteMergeProperty =
OnceAbsoluteMergeProperty.build(headClazz.getAnnotation(OnceAbsoluteMerge.class));
ColumnWidth parentColumnWidth = headClazz.getAnnotation(ColumnWidth.class);
HeadStyle parentHeadStyle = headClazz.getAnnotation(HeadStyle.class);
HeadFontStyle parentHeadFontStyle = headClazz.getAnnotation(HeadFontStyle.class);
for (Map.Entry<Integer, Head> entry : getHeadMap().entrySet()) {
Head headData = entry.getValue();
if (headData == null) {
throw new IllegalArgumentException(
"Passing in the class and list the head, the two must be the same size.");
}
Field field = headData.getField();
ColumnWidth columnWidth = field.getAnnotation(ColumnWidth.class);
if (columnWidth == null) {
columnWidth = parentColumnWidth;
}
headData.setColumnWidthProperty(ColumnWidthProperty.build(columnWidth));
HeadStyle headStyle = field.getAnnotation(HeadStyle.class);
if (headStyle == null) {
headStyle = parentHeadStyle;
}
headData.setHeadStyleProperty(StyleProperty.build(headStyle));
HeadFontStyle headFontStyle = field.getAnnotation(HeadFontStyle.class);
if (headFontStyle == null) {
headFontStyle = parentHeadFontStyle;
}
headData.setHeadFontProperty(FontProperty.build(headFontStyle));
headData.setLoopMergeProperty(LoopMergeProperty.build(field.getAnnotation(ContentLoopMerge.class)));
}
}
/**
* Calculate all cells that need to be merged
*
* @return cells that need to be merged
*/
public List<CellRange> headCellRangeList() {
List<CellRange> cellRangeList = new ArrayList<CellRange>();
Set<String> alreadyRangeSet = new HashSet<String>();
List<Head> headList = new ArrayList<Head>(getHeadMap().values());
for (int i = 0; i < headList.size(); i++) {
Head head = headList.get(i);
List<String> headNameList = head.getHeadNameList();
for (int j = 0; j < headNameList.size(); j++) {
if (alreadyRangeSet.contains(i + "-" + j)) {
continue;
}
alreadyRangeSet.add(i + "-" + j);
String headName = headNameList.get(j);
int lastCol = i;
int lastRow = j;
for (int k = i + 1; k < headList.size(); k++) {
String key = k + "-" + j;
if (headList.get(k).getHeadNameList().get(j).equals(headName) && !alreadyRangeSet.contains(key)) {
alreadyRangeSet.add(key);
lastCol = k;
} else {
break;
}
}
Set<String> tempAlreadyRangeSet = new HashSet<>();
outer:
for (int k = j + 1; k < headNameList.size(); k++) {
for (int l = i; l <= lastCol; l++) {
String key = l + "-" + k;
if (headList.get(l).getHeadNameList().get(k).equals(headName) && !alreadyRangeSet.contains(
key)) {
tempAlreadyRangeSet.add(l + "-" + k);
} else {
break outer;
}
}
lastRow = k;
alreadyRangeSet.addAll(tempAlreadyRangeSet);
}
if (j == lastRow && i == lastCol) {
continue;
}
cellRangeList
.add(new CellRange(j, lastRow, head.getColumnIndex(), headList.get(lastCol).getColumnIndex()));
}
}
return cellRangeList;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java | easyexcel-core/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java | package com.alibaba.excel.write.executor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.BeanMapUtils;
import com.alibaba.excel.util.ClassUtils;
import com.alibaba.excel.util.FieldUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.util.WriteHandlerUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.alibaba.excel.write.metadata.fill.AnalysisCell;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import com.alibaba.excel.util.PoiUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
/**
* 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 final Map<UniqueDataFlagKey, List<AnalysisCell>> templateAnalysisCache = MapUtils.newHashMap();
/**
* Collection fields to replace in the template
*/
private final Map<UniqueDataFlagKey, List<AnalysisCell>> templateCollectionAnalysisCache = MapUtils.newHashMap();
/**
* Style cache for collection fields
*/
private final Map<UniqueDataFlagKey, Map<AnalysisCell, CellStyle>> collectionFieldStyleCache
= MapUtils.newHashMap();
/**
* Row height cache for collection
*/
private final Map<UniqueDataFlagKey, Short> collectionRowHeightCache = MapUtils.newHashMap();
/**
* Last index cache for collection fields
*/
private final Map<UniqueDataFlagKey, Map<AnalysisCell, Integer>> collectionLastIndexCache = MapUtils.newHashMap();
private final Map<UniqueDataFlagKey, Integer> relativeRowIndexMap = MapUtils.newHashMap();
/**
* The unique data encoding for this fill
*/
private UniqueDataFlagKey currentUniqueDataFlag;
public ExcelWriteFillExecutor(WriteContext writeContext) {
super(writeContext);
}
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);
}
}
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);
}
private void increaseRowIndex(Map<UniqueDataFlagKey, List<AnalysisCell>> templateAnalysisCache, int number,
int maxRowIndex) {
for (Map.Entry<UniqueDataFlagKey, List<AnalysisCell>> entry : templateAnalysisCache.entrySet()) {
UniqueDataFlagKey uniqueDataFlagKey = entry.getKey();
if (!Objects.equals(currentUniqueDataFlag.getSheetNo(), uniqueDataFlagKey.getSheetNo()) || !Objects.equals(
currentUniqueDataFlag.getSheetName(), uniqueDataFlagKey.getSheetName())) {
continue;
}
for (AnalysisCell analysisCell : entry.getValue()) {
if (analysisCell.getRowIndex() > maxRowIndex) {
analysisCell.setRowIndex(analysisCell.getRowIndex() + number);
}
}
}
}
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,
writeContext.currentWriteHolder());
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,
writeContext.currentWriteHolder());
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);
}
}
private Integer getRelativeRowIndex() {
Integer relativeRowIndex = relativeRowIndexMap.get(currentUniqueDataFlag);
if (relativeRowIndex == null) {
relativeRowIndex = 0;
} else {
relativeRowIndex++;
}
relativeRowIndexMap.put(currentUniqueDataFlag, relativeRowIndex);
return relativeRowIndex;
}
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());
}
}
private Cell createCellIfNecessary(Row row, Integer lastColumnIndex,
CellWriteHandlerContext cellWriteHandlerContext) {
Cell cell = row.getCell(lastColumnIndex);
if (cell != null) {
return cell;
}
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
cell = row.createCell(lastColumnIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
return cell;
}
private Row createRowIfNecessary(Sheet sheet, Sheet cachedSheet, Integer lastRowIndex, FillConfig fillConfig,
AnalysisCell analysisCell, boolean isOriginalCell, RowWriteHandlerContext rowWriteHandlerContext) {
rowWriteHandlerContext.setRowIndex(lastRowIndex);
Row row = sheet.getRow(lastRowIndex);
if (row != null) {
checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
rowWriteHandlerContext.setRow(row);
return row;
}
row = cachedSheet.getRow(lastRowIndex);
if (row == null) {
rowWriteHandlerContext.setRowIndex(lastRowIndex);
WriteHandlerUtils.beforeRowCreate(rowWriteHandlerContext);
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);
}
}
rowWriteHandlerContext.setRow(row);
checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
WriteHandlerUtils.afterRowCreate(rowWriteHandlerContext);
} else {
checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
rowWriteHandlerContext.setRow(row);
}
return row;
}
private void checkRowHeight(AnalysisCell analysisCell, FillConfig fillConfig, boolean isOriginalCell, Row row) {
if (!analysisCell.getFirstRow() || !WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection())) {
return;
}
// fix https://github.com/alibaba/easyexcel/issues/1869
if (isOriginalCell && PoiUtils.customHeight(row)) {
collectionRowHeightCache.put(currentUniqueDataFlag, row.getHeight());
return;
}
if (fillConfig.getAutoStyle()) {
Short rowHeight = collectionRowHeightCache.get(currentUniqueDataFlag);
if (rowHeight != null) {
row.setHeight(rowHeight);
}
}
}
private List<AnalysisCell> readTemplateData(Map<UniqueDataFlagKey, List<AnalysisCell>> analysisCache) {
List<AnalysisCell> analysisCellList = analysisCache.get(currentUniqueDataFlag);
if (analysisCellList != null) {
return analysisCellList;
}
Sheet sheet = writeContext.writeSheetHolder().getCachedSheet();
Map<UniqueDataFlagKey, Set<Integer>> firstRowCache = MapUtils.newHashMapWithExpectedSize(8);
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;
}
String preparedData = prepareData(cell, i, j, firstRowCache);
// Prevent empty data from not being replaced
if (preparedData != null) {
cell.setCellValue(preparedData);
}
}
}
return analysisCache.get(currentUniqueDataFlag);
}
/**
* 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;
}
// fix https://github.com/alibaba/easyexcel/issues/1552
// When read template, XLSX data may be in `is` labels, and set the time set in `v` label, lead to can't set
// 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);
}
private String dealAnalysisCell(AnalysisCell analysisCell, String value, int rowIndex, int lastPrepareDataIndex,
int length, Map<UniqueDataFlagKey, Set<Integer>> firstRowCache, StringBuilder preparedData) {
if (analysisCell != null) {
if (lastPrepareDataIndex == length) {
analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
} else {
analysisCell.getPrepareDataList().add(convertPrepareData(value.substring(lastPrepareDataIndex)));
analysisCell.setOnlyOneVariable(Boolean.FALSE);
}
UniqueDataFlagKey uniqueDataFlag = uniqueDataFlag(writeContext.writeSheetHolder(),
analysisCell.getPrefix());
if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) {
List<AnalysisCell> analysisCellList = templateAnalysisCache.computeIfAbsent(uniqueDataFlag,
key -> ListUtils.newArrayList());
analysisCellList.add(analysisCell);
} else {
Set<Integer> uniqueFirstRowCache = firstRowCache.computeIfAbsent(uniqueDataFlag,
key -> new HashSet<>());
if (!uniqueFirstRowCache.contains(rowIndex)) {
analysisCell.setFirstRow(Boolean.TRUE);
uniqueFirstRowCache.add(rowIndex);
}
List<AnalysisCell> collectionAnalysisCellList = templateCollectionAnalysisCache.computeIfAbsent(
uniqueDataFlag, key -> ListUtils.newArrayList());
collectionAnalysisCellList.add(analysisCell);
}
return preparedData.toString();
}
return null;
}
private AnalysisCell initAnalysisCell(Integer rowIndex, Integer columnIndex) {
AnalysisCell analysisCell = new AnalysisCell();
analysisCell.setRowIndex(rowIndex);
analysisCell.setColumnIndex(columnIndex);
analysisCell.setOnlyOneVariable(Boolean.TRUE);
List<String> variableList = ListUtils.newArrayList();
analysisCell.setVariableList(variableList);
List<String> prepareDataList = ListUtils.newArrayList();
analysisCell.setPrepareDataList(prepareDataList);
analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COMMON);
analysisCell.setFirstRow(Boolean.FALSE);
return analysisCell;
}
private String convertPrepareData(String prepareData) {
prepareData = prepareData.replaceAll(ESCAPE_FILL_PREFIX, FILL_PREFIX);
prepareData = prepareData.replaceAll(ESCAPE_FILL_SUFFIX, FILL_SUFFIX);
return prepareData;
}
private UniqueDataFlagKey uniqueDataFlag(WriteSheetHolder writeSheetHolder, String wrapperName) {
return new UniqueDataFlagKey(writeSheetHolder.getSheetNo(), writeSheetHolder.getSheetName(), wrapperName);
}
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public static class UniqueDataFlagKey {
private Integer sheetNo;
private String sheetName;
private String wrapperName;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java | easyexcel-core/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java | package com.alibaba.excel.write.executor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.metadata.FieldCache;
import com.alibaba.excel.metadata.FieldWrapper;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.support.cglib.beans.BeanMap;
import com.alibaba.excel.util.BeanMapUtils;
import com.alibaba.excel.util.ClassUtils;
import com.alibaba.excel.util.FieldUtils;
import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.util.WriteHandlerUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.alibaba.excel.write.metadata.CollectionRowData;
import com.alibaba.excel.write.metadata.MapRowData;
import com.alibaba.excel.write.metadata.RowData;
import com.alibaba.excel.write.metadata.holder.WriteHolder;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* Add the data into excel
*
* @author Jiaju Zhuang
*/
public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
public ExcelWriteAddExecutor(WriteContext writeContext) {
super(writeContext);
}
public void add(Collection<?> data) {
if (CollectionUtils.isEmpty(data)) {
data = new ArrayList<>();
}
WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder();
int newRowIndex = writeSheetHolder.getNewRowIndexAndStartDoWrite();
if (writeSheetHolder.isNew() && !writeSheetHolder.getExcelWriteHeadProperty().hasHead()) {
newRowIndex += writeContext.currentWriteHolder().relativeHeadRowIndex();
}
int relativeRowIndex = 0;
for (Object oneRowData : data) {
int lastRowIndex = relativeRowIndex + newRowIndex;
addOneRowOfDataToExcel(oneRowData, lastRowIndex, relativeRowIndex);
relativeRowIndex++;
}
}
private void addOneRowOfDataToExcel(Object oneRowData, int rowIndex, int relativeRowIndex) {
if (oneRowData == null) {
return;
}
RowWriteHandlerContext rowWriteHandlerContext = WriteHandlerUtils.createRowWriteHandlerContext(writeContext,
rowIndex, relativeRowIndex, Boolean.FALSE);
WriteHandlerUtils.beforeRowCreate(rowWriteHandlerContext);
Row row = WorkBookUtil.createRow(writeContext.writeSheetHolder().getSheet(), rowIndex);
rowWriteHandlerContext.setRow(row);
WriteHandlerUtils.afterRowCreate(rowWriteHandlerContext);
if (oneRowData instanceof Collection<?>) {
addBasicTypeToExcel(new CollectionRowData((Collection<?>)oneRowData), row, rowIndex, relativeRowIndex);
} else if (oneRowData instanceof Map) {
addBasicTypeToExcel(new MapRowData((Map<Integer, ?>)oneRowData), row, rowIndex, relativeRowIndex);
} else {
addJavaObjectToExcel(oneRowData, row, rowIndex, relativeRowIndex);
}
WriteHandlerUtils.afterRowDispose(rowWriteHandlerContext);
}
private void addBasicTypeToExcel(RowData oneRowData, Row row, int rowIndex, int relativeRowIndex) {
if (oneRowData.isEmpty()) {
return;
}
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
int dataIndex = 0;
int maxCellIndex = -1;
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
if (dataIndex >= oneRowData.size()) {
return;
}
int columnIndex = entry.getKey();
Head head = entry.getValue();
doAddBasicTypeToExcel(oneRowData, head, row, rowIndex, relativeRowIndex, dataIndex++, columnIndex);
maxCellIndex = Math.max(maxCellIndex, columnIndex);
}
// Finish
if (dataIndex >= oneRowData.size()) {
return;
}
// fix https://github.com/alibaba/easyexcel/issues/1702
// If there is data, it is written to the next cell
maxCellIndex++;
int size = oneRowData.size() - dataIndex;
for (int i = 0; i < size; i++) {
doAddBasicTypeToExcel(oneRowData, null, row, rowIndex, relativeRowIndex, dataIndex++, maxCellIndex++);
}
}
private void doAddBasicTypeToExcel(RowData oneRowData, Head head, Row row, int rowIndex, int relativeRowIndex,
int dataIndex, int columnIndex) {
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(null,
writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadClazz(),
head == null ? null : head.getFieldName(), writeContext.currentWriteHolder());
CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(writeContext,
row, rowIndex, head, columnIndex, relativeRowIndex, Boolean.FALSE, excelContentProperty);
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
Cell cell = WorkBookUtil.createCell(row, columnIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
cellWriteHandlerContext.setOriginalValue(oneRowData.get(dataIndex));
cellWriteHandlerContext.setOriginalFieldClass(
FieldUtils.getFieldClass(cellWriteHandlerContext.getOriginalValue()));
converterAndSet(cellWriteHandlerContext);
WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
}
private void addJavaObjectToExcel(Object oneRowData, Row row, int rowIndex, int relativeRowIndex) {
WriteHolder currentWriteHolder = writeContext.currentWriteHolder();
BeanMap beanMap = BeanMapUtils.create(oneRowData);
// Bean the contains of the Map Key method with poor performance,So to create a keySet here
Set<String> beanKeySet = new HashSet<>(beanMap.keySet());
Set<String> beanMapHandledSet = new HashSet<>();
int maxCellIndex = -1;
// If it's a class it needs to be cast by type
if (HeadKindEnum.CLASS.equals(writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadKind())) {
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
int columnIndex = entry.getKey();
Head head = entry.getValue();
String name = head.getFieldName();
if (!beanKeySet.contains(name)) {
continue;
}
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(beanMap,
currentWriteHolder.excelWriteHeadProperty().getHeadClazz(), name, currentWriteHolder);
CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(
writeContext, row, rowIndex, head, columnIndex, relativeRowIndex, Boolean.FALSE,
excelContentProperty);
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
Cell cell = WorkBookUtil.createCell(row, columnIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
cellWriteHandlerContext.setOriginalValue(beanMap.get(name));
cellWriteHandlerContext.setOriginalFieldClass(head.getField().getType());
converterAndSet(cellWriteHandlerContext);
WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
beanMapHandledSet.add(name);
maxCellIndex = Math.max(maxCellIndex, columnIndex);
}
}
// Finish
if (beanMapHandledSet.size() == beanMap.size()) {
return;
}
maxCellIndex++;
FieldCache fieldCache = ClassUtils.declaredFields(oneRowData.getClass(), writeContext.currentWriteHolder());
for (Map.Entry<Integer, FieldWrapper> entry : fieldCache.getSortedFieldMap().entrySet()) {
FieldWrapper field = entry.getValue();
String fieldName = field.getFieldName();
boolean uselessData = !beanKeySet.contains(fieldName) || beanMapHandledSet.contains(fieldName);
if (uselessData) {
continue;
}
Object value = beanMap.get(fieldName);
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(beanMap,
currentWriteHolder.excelWriteHeadProperty().getHeadClazz(), fieldName, currentWriteHolder);
CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(
writeContext, row, rowIndex, null, maxCellIndex, relativeRowIndex, Boolean.FALSE, excelContentProperty);
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
// fix https://github.com/alibaba/easyexcel/issues/1870
// If there is data, it is written to the next cell
Cell cell = WorkBookUtil.createCell(row, maxCellIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
cellWriteHandlerContext.setOriginalValue(value);
cellWriteHandlerContext.setOriginalFieldClass(FieldUtils.getFieldClass(beanMap, fieldName, value));
converterAndSet(cellWriteHandlerContext);
WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
maxCellIndex++;
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/executor/ExcelWriteExecutor.java | easyexcel-core/src/main/java/com/alibaba/excel/write/executor/ExcelWriteExecutor.java | package com.alibaba.excel.write.executor;
/**
* Excel write Executor
*
* @author Jiaju Zhuang
*/
public interface ExcelWriteExecutor {
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java | easyexcel-core/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java | package com.alibaba.excel.write.executor;
import java.util.List;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.converters.NullableObjectConverter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.exception.ExcelWriteDataConvertException;
import com.alibaba.excel.metadata.data.CommentData;
import com.alibaba.excel.metadata.data.FormulaData;
import com.alibaba.excel.metadata.data.HyperlinkData;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileTypeUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.util.WriteHandlerUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
/**
* Excel write Executor
*
* @author Jiaju Zhuang
*/
public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor {
protected WriteContext writeContext;
public AbstractExcelWriteExecutor(WriteContext writeContext) {
this.writeContext = writeContext;
}
/**
* Transform the data and then to set into the cell
*
* @param cellWriteHandlerContext context
*/
protected void converterAndSet(CellWriteHandlerContext cellWriteHandlerContext) {
WriteCellData<?> cellData = convert(cellWriteHandlerContext);
cellWriteHandlerContext.setCellDataList(ListUtils.newArrayList(cellData));
cellWriteHandlerContext.setFirstCellData(cellData);
WriteHandlerUtils.afterCellDataConverted(cellWriteHandlerContext);
// Fill in picture information
fillImage(cellWriteHandlerContext, cellData.getImageDataList());
// Fill in comment information
fillComment(cellWriteHandlerContext, cellData.getCommentData());
// Fill in hyper link information
fillHyperLink(cellWriteHandlerContext, cellData.getHyperlinkData());
// Fill in formula information
fillFormula(cellWriteHandlerContext, cellData.getFormulaData());
// Fill index
cellData.setRowIndex(cellWriteHandlerContext.getRowIndex());
cellData.setColumnIndex(cellWriteHandlerContext.getColumnIndex());
if (cellData.getType() == null) {
cellData.setType(CellDataTypeEnum.EMPTY);
}
Cell cell = cellWriteHandlerContext.getCell();
switch (cellData.getType()) {
case STRING:
cell.setCellValue(cellData.getStringValue());
return;
case BOOLEAN:
cell.setCellValue(cellData.getBooleanValue());
return;
case NUMBER:
cell.setCellValue(cellData.getNumberValue().doubleValue());
return;
case DATE:
cell.setCellValue(cellData.getDateValue());
return;
case RICH_TEXT_STRING:
cell.setCellValue(StyleUtil
.buildRichTextString(writeContext.writeWorkbookHolder(), cellData.getRichTextStringDataValue()));
return;
case EMPTY:
return;
default:
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Not supported data:" + cellWriteHandlerContext.getOriginalValue() + " return type:"
+ cellData.getType()
+ "at row:" + cellWriteHandlerContext.getRowIndex());
}
}
private void fillFormula(CellWriteHandlerContext cellWriteHandlerContext, FormulaData formulaData) {
if (formulaData == null) {
return;
}
Cell cell = cellWriteHandlerContext.getCell();
if (formulaData.getFormulaValue() != null) {
cell.setCellFormula(formulaData.getFormulaValue());
}
}
private void fillHyperLink(CellWriteHandlerContext cellWriteHandlerContext, HyperlinkData hyperlinkData) {
if (hyperlinkData == null) {
return;
}
Integer rowIndex = cellWriteHandlerContext.getRowIndex();
Integer columnIndex = cellWriteHandlerContext.getColumnIndex();
Workbook workbook = cellWriteHandlerContext.getWriteWorkbookHolder().getWorkbook();
Cell cell = cellWriteHandlerContext.getCell();
CreationHelper helper = workbook.getCreationHelper();
Hyperlink hyperlink = helper.createHyperlink(StyleUtil.getHyperlinkType(hyperlinkData.getHyperlinkType()));
hyperlink.setAddress(hyperlinkData.getAddress());
hyperlink.setFirstRow(StyleUtil.getCellCoordinate(rowIndex, hyperlinkData.getFirstRowIndex(),
hyperlinkData.getRelativeFirstRowIndex()));
hyperlink.setFirstColumn(StyleUtil.getCellCoordinate(columnIndex, hyperlinkData.getFirstColumnIndex(),
hyperlinkData.getRelativeFirstColumnIndex()));
hyperlink.setLastRow(StyleUtil.getCellCoordinate(rowIndex, hyperlinkData.getLastRowIndex(),
hyperlinkData.getRelativeLastRowIndex()));
hyperlink.setLastColumn(StyleUtil.getCellCoordinate(columnIndex, hyperlinkData.getLastColumnIndex(),
hyperlinkData.getRelativeLastColumnIndex()));
cell.setHyperlink(hyperlink);
}
private void fillComment(CellWriteHandlerContext cellWriteHandlerContext, CommentData commentData) {
if (commentData == null) {
return;
}
ClientAnchor anchor;
Integer rowIndex = cellWriteHandlerContext.getRowIndex();
Integer columnIndex = cellWriteHandlerContext.getColumnIndex();
Sheet sheet = cellWriteHandlerContext.getWriteSheetHolder().getSheet();
Cell cell = cellWriteHandlerContext.getCell();
if (writeContext.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.XLSX) {
anchor = new XSSFClientAnchor(StyleUtil.getCoordinate(commentData.getLeft()),
StyleUtil.getCoordinate(commentData.getTop()),
StyleUtil.getCoordinate(commentData.getRight()),
StyleUtil.getCoordinate(commentData.getBottom()),
StyleUtil.getCellCoordinate(columnIndex, commentData.getFirstColumnIndex(),
commentData.getRelativeFirstColumnIndex()),
StyleUtil.getCellCoordinate(rowIndex, commentData.getFirstRowIndex(),
commentData.getRelativeFirstRowIndex()),
StyleUtil.getCellCoordinate(columnIndex, commentData.getLastColumnIndex(),
commentData.getRelativeLastColumnIndex()) + 1,
StyleUtil.getCellCoordinate(rowIndex, commentData.getLastRowIndex(),
commentData.getRelativeLastRowIndex()) + 1);
} else {
anchor = new HSSFClientAnchor(StyleUtil.getCoordinate(commentData.getLeft()),
StyleUtil.getCoordinate(commentData.getTop()),
StyleUtil.getCoordinate(commentData.getRight()),
StyleUtil.getCoordinate(commentData.getBottom()),
(short)StyleUtil.getCellCoordinate(columnIndex, commentData.getFirstColumnIndex(),
commentData.getRelativeFirstColumnIndex()),
StyleUtil.getCellCoordinate(rowIndex, commentData.getFirstRowIndex(),
commentData.getRelativeFirstRowIndex()),
(short)(StyleUtil.getCellCoordinate(columnIndex, commentData.getLastColumnIndex(),
commentData.getRelativeLastColumnIndex()) + 1),
StyleUtil.getCellCoordinate(rowIndex, commentData.getLastRowIndex(),
commentData.getRelativeLastRowIndex()) + 1);
}
Comment comment = sheet.createDrawingPatriarch().createCellComment(anchor);
if (commentData.getRichTextStringData() != null) {
comment.setString(
StyleUtil.buildRichTextString(writeContext.writeWorkbookHolder(), commentData.getRichTextStringData()));
}
if (commentData.getAuthor() != null) {
comment.setAuthor(commentData.getAuthor());
}
cell.setCellComment(comment);
}
protected void fillImage(CellWriteHandlerContext cellWriteHandlerContext, List<ImageData> imageDataList) {
if (CollectionUtils.isEmpty(imageDataList)) {
return;
}
Integer rowIndex = cellWriteHandlerContext.getRowIndex();
Integer columnIndex = cellWriteHandlerContext.getColumnIndex();
Sheet sheet = cellWriteHandlerContext.getWriteSheetHolder().getSheet();
Workbook workbook = cellWriteHandlerContext.getWriteWorkbookHolder().getWorkbook();
Drawing<?> drawing = sheet.getDrawingPatriarch();
if (drawing == null) {
drawing = sheet.createDrawingPatriarch();
}
CreationHelper helper = sheet.getWorkbook().getCreationHelper();
for (ImageData imageData : imageDataList) {
int index = workbook.addPicture(imageData.getImage(),
FileTypeUtils.getImageTypeFormat(imageData.getImage()));
ClientAnchor anchor = helper.createClientAnchor();
if (imageData.getTop() != null) {
anchor.setDy1(StyleUtil.getCoordinate(imageData.getTop()));
}
if (imageData.getRight() != null) {
anchor.setDx2(-StyleUtil.getCoordinate(imageData.getRight()));
}
if (imageData.getBottom() != null) {
anchor.setDy2(-StyleUtil.getCoordinate(imageData.getBottom()));
}
if (imageData.getLeft() != null) {
anchor.setDx1(StyleUtil.getCoordinate(imageData.getLeft()));
}
anchor.setRow1(StyleUtil.getCellCoordinate(rowIndex, imageData.getFirstRowIndex(),
imageData.getRelativeFirstRowIndex()));
anchor.setCol1(StyleUtil.getCellCoordinate(columnIndex, imageData.getFirstColumnIndex(),
imageData.getRelativeFirstColumnIndex()));
anchor.setRow2(StyleUtil.getCellCoordinate(rowIndex, imageData.getLastRowIndex(),
imageData.getRelativeLastRowIndex()) + 1);
anchor.setCol2(StyleUtil.getCellCoordinate(columnIndex, imageData.getLastColumnIndex(),
imageData.getRelativeLastColumnIndex()) + 1);
if (imageData.getAnchorType() != null) {
anchor.setAnchorType(imageData.getAnchorType().getValue());
}
drawing.createPicture(anchor, index);
}
}
protected WriteCellData<?> convert(CellWriteHandlerContext cellWriteHandlerContext) {
// This means that the user has defined the data.
if (cellWriteHandlerContext.getOriginalFieldClass() == WriteCellData.class) {
if (cellWriteHandlerContext.getOriginalValue() == null) {
return new WriteCellData<>(CellDataTypeEnum.EMPTY);
}
WriteCellData<?> cellDataValue = (WriteCellData<?>)cellWriteHandlerContext.getOriginalValue();
if (cellDataValue.getType() != null) {
// Configuration information may not be read here
fillProperty(cellDataValue, cellWriteHandlerContext.getExcelContentProperty());
return cellDataValue;
} else {
if (cellDataValue.getData() == null) {
cellDataValue.setType(CellDataTypeEnum.EMPTY);
return cellDataValue;
}
}
WriteCellData<?> cellDataReturn = doConvert(cellWriteHandlerContext);
if (cellDataValue.getImageDataList() != null) {
cellDataReturn.setImageDataList(cellDataValue.getImageDataList());
}
if (cellDataValue.getCommentData() != null) {
cellDataReturn.setCommentData(cellDataValue.getCommentData());
}
if (cellDataValue.getHyperlinkData() != null) {
cellDataReturn.setHyperlinkData(cellDataValue.getHyperlinkData());
}
// The formula information is subject to user input
if (cellDataValue.getFormulaData() != null) {
cellDataReturn.setFormulaData(cellDataValue.getFormulaData());
}
if (cellDataValue.getWriteCellStyle() != null) {
cellDataReturn.setWriteCellStyle(cellDataValue.getWriteCellStyle());
}
return cellDataReturn;
}
return doConvert(cellWriteHandlerContext);
}
private void fillProperty(WriteCellData<?> cellDataValue, ExcelContentProperty excelContentProperty) {
switch (cellDataValue.getType()) {
case DATE:
String dateFormat = null;
if (excelContentProperty != null && excelContentProperty.getDateTimeFormatProperty() != null) {
dateFormat = excelContentProperty.getDateTimeFormatProperty().getFormat();
}
WorkBookUtil.fillDataFormat(cellDataValue, dateFormat, DateUtils.defaultDateFormat);
return;
case NUMBER:
String numberFormat = null;
if (excelContentProperty != null && excelContentProperty.getNumberFormatProperty() != null) {
numberFormat = excelContentProperty.getNumberFormatProperty().getFormat();
}
WorkBookUtil.fillDataFormat(cellDataValue, numberFormat, null);
return;
default:
return;
}
}
private WriteCellData<?> doConvert(CellWriteHandlerContext cellWriteHandlerContext) {
ExcelContentProperty excelContentProperty = cellWriteHandlerContext.getExcelContentProperty();
Converter<?> converter = null;
if (excelContentProperty != null) {
converter = excelContentProperty.getConverter();
}
if (converter == null) {
// csv is converted to string by default
if (writeContext.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.CSV) {
cellWriteHandlerContext.setTargetCellDataType(CellDataTypeEnum.STRING);
}
converter = writeContext.currentWriteHolder().converterMap().get(
ConverterKeyBuild.buildKey(cellWriteHandlerContext.getOriginalFieldClass(),
cellWriteHandlerContext.getTargetCellDataType()));
}
if (cellWriteHandlerContext.getOriginalValue() == null && !(converter instanceof NullableObjectConverter)) {
return new WriteCellData<>(CellDataTypeEnum.EMPTY);
}
if (converter == null) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Can not find 'Converter' support class " + cellWriteHandlerContext.getOriginalFieldClass()
.getSimpleName() + ".");
}
WriteCellData<?> cellData;
try {
cellData = ((Converter<Object>)converter).convertToExcelData(
new WriteConverterContext<>(cellWriteHandlerContext.getOriginalValue(), excelContentProperty,
writeContext));
} catch (Exception e) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Convert data:" + cellWriteHandlerContext.getOriginalValue() + " error, at row:"
+ cellWriteHandlerContext.getRowIndex(), e);
}
if (cellData == null || cellData.getType() == null) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Convert data:" + cellWriteHandlerContext.getOriginalValue()
+ " return is null or return type is null, at row:"
+ cellWriteHandlerContext.getRowIndex());
}
return cellData;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractWorkbookWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractWorkbookWriteHandler.java | package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* Abstract workbook write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link WorkbookWriteHandler}
**/
@Deprecated
public abstract class AbstractWorkbookWriteHandler implements WorkbookWriteHandler {
@Override
public void beforeWorkbookCreate() {
}
@Override
public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
}
@Override
public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractSheetWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractSheetWriteHandler.java | package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* Abstract sheet write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link SheetWriteHandler}
**/
@Deprecated
public abstract class AbstractSheetWriteHandler implements SheetWriteHandler {
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java | package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Row;
/**
* intercepts handle row creation
*
* @author Jiaju Zhuang
*/
public interface RowWriteHandler extends WriteHandler {
/**
* Called before create the row
*
* @param context
*/
default void beforeRowCreate(RowWriteHandlerContext context) {
beforeRowCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRowIndex(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called before create the row
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param rowIndex
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead Nullable.It is null in the case of fill data.
*/
default void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the row is created
*
* @param context
*/
default void afterRowCreate(RowWriteHandlerContext context) {
afterRowCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the row is created
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param row
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead Nullable.It is null in the case of fill data.
*/
default void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after all operations on the row have been completed.
* In the case of the fill , may be called many times.
*
* @param context
*/
default void afterRowDispose(RowWriteHandlerContext context) {
afterRowDispose(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after all operations on the row have been completed.
* In the case of the fill , may be called many times.
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param row
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead Nullable.It is null in the case of fill data.
*/
default void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java | package com.alibaba.excel.write.handler;
import java.util.List;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* intercepts handle cell creation
*
* @author Jiaju Zhuang
*/
public interface CellWriteHandler extends WriteHandler {
/**
* Called before create the cell
*
* @param context
*/
default void beforeCellCreate(CellWriteHandlerContext context) {
beforeCellCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getHeadData(), context.getColumnIndex(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called before create the cell
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param row
* @param head Nullable.It is null in the case of fill data and without head.
* @param columnIndex
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the cell is created
*
* @param context
*/
default void afterCellCreate(CellWriteHandlerContext context) {
afterCellCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getCell(),
context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the cell is created
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param cell
* @param head Nullable.It is null in the case of fill data and without head.
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the cell data is converted
*
* @param context
*/
default void afterCellDataConverted(CellWriteHandlerContext context) {
WriteCellData<?> writeCellData = CollectionUtils.isNotEmpty(context.getCellDataList()) ? context
.getCellDataList().get(0) : null;
afterCellDataConverted(context.getWriteSheetHolder(), context.getWriteTableHolder(), writeCellData,
context.getCell(), context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the cell data is converted
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param cell
* @param head Nullable.It is null in the case of fill data and without head.
* @param cellData Nullable.It is null in the case of add header.
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after all operations on the cell have been completed
*
* @param context
*/
default void afterCellDispose(CellWriteHandlerContext context) {
afterCellDispose(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getCellDataList(),
context.getCell(), context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after all operations on the cell have been completed
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param cell
* @param head Nullable.It is null in the case of fill data and without head.
* @param cellDataList Nullable.It is null in the case of add header.There may be several when fill the data.
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java | package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* intercepts handle sheet creation
*
* @author Jiaju Zhuang
*/
public interface SheetWriteHandler extends WriteHandler {
/**
* Called before create the sheet
*
* @param context
*/
default void beforeSheetCreate(SheetWriteHandlerContext context) {
beforeSheetCreate(context.getWriteWorkbookHolder(), context.getWriteSheetHolder());
}
/**
* Called before create the sheet
*
* @param writeWorkbookHolder
* @param writeSheetHolder
*/
default void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}
/**
* Called after the sheet is created
*
* @param context
*/
default void afterSheetCreate(SheetWriteHandlerContext context) {
afterSheetCreate(context.getWriteWorkbookHolder(), context.getWriteSheetHolder());
}
/**
* Called after the sheet is created
*
* @param writeWorkbookHolder
* @param writeSheetHolder
*/
default void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java | package com.alibaba.excel.write.handler;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.impl.DefaultRowWriteHandler;
import com.alibaba.excel.write.handler.impl.DimensionWorkbookWriteHandler;
import com.alibaba.excel.write.handler.impl.FillStyleCellWriteHandler;
import com.alibaba.excel.write.style.DefaultStyle;
/**
* Load default handler
*
* @author Jiaju Zhuang
*/
public class DefaultWriteHandlerLoader {
public static final List<WriteHandler> DEFAULT_WRITE_HANDLER_LIST = new ArrayList<>();
static {
DEFAULT_WRITE_HANDLER_LIST.add(new DimensionWorkbookWriteHandler());
DEFAULT_WRITE_HANDLER_LIST.add(new DefaultRowWriteHandler());
DEFAULT_WRITE_HANDLER_LIST.add(new FillStyleCellWriteHandler());
}
/**
* Load default handler
*
* @return
*/
public static List<WriteHandler> loadDefaultHandler(Boolean useDefaultStyle, ExcelTypeEnum excelType) {
List<WriteHandler> handlerList = new ArrayList<>();
switch (excelType) {
case XLSX:
handlerList.add(new DimensionWorkbookWriteHandler());
handlerList.add(new DefaultRowWriteHandler());
handlerList.add(new FillStyleCellWriteHandler());
if (useDefaultStyle) {
handlerList.add(new DefaultStyle());
}
break;
case XLS:
handlerList.add(new DefaultRowWriteHandler());
handlerList.add(new FillStyleCellWriteHandler());
if (useDefaultStyle) {
handlerList.add(new DefaultStyle());
}
break;
case CSV:
handlerList.add(new DefaultRowWriteHandler());
handlerList.add(new FillStyleCellWriteHandler());
break;
default:
break;
}
return handlerList;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java | package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* intercepts handle Workbook creation
*
* @author Jiaju Zhuang
*/
public interface WorkbookWriteHandler extends WriteHandler {
/**
* Called before create the workbook
*
* @param context
*/
default void beforeWorkbookCreate(WorkbookWriteHandlerContext context) {
beforeWorkbookCreate();
}
/**
* Called before create the workbook
*/
default void beforeWorkbookCreate() {}
/**
* Called after the workbook is created
*
* @param context
*/
default void afterWorkbookCreate(WorkbookWriteHandlerContext context) {
afterWorkbookCreate(context.getWriteWorkbookHolder());
}
/**
* Called after the workbook is created
*
* @param writeWorkbookHolder
*/
default void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {}
/**
* Called after all operations on the workbook have been completed
*
* @param context
*/
default void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
afterWorkbookDispose(context.getWriteWorkbookHolder());
}
/**
* Called after all operations on the workbook have been completed
*
* @param writeWorkbookHolder
*/
default void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractRowWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractRowWriteHandler.java | package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Row;
/**
* Abstract row write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link RowWriteHandler}
**/
@Deprecated
public abstract class AbstractRowWriteHandler implements RowWriteHandler {
@Override
public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java | package com.alibaba.excel.write.handler;
import java.util.List;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* Abstract cell write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link CellWriteHandler}
**/
@Deprecated
public abstract class AbstractCellWriteHandler implements CellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/WriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/WriteHandler.java | package com.alibaba.excel.write.handler;
import com.alibaba.excel.event.Handler;
/**
* intercepts handle excel write
*
* @author Jiaju Zhuang
*/
public interface WriteHandler extends Handler {}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/SheetHandlerExecutionChain.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/SheetHandlerExecutionChain.java | package com.alibaba.excel.write.handler.chain;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the sheet handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class SheetHandlerExecutionChain {
/**
* next chain
*/
private SheetHandlerExecutionChain next;
/**
* handler
*/
private SheetWriteHandler handler;
public SheetHandlerExecutionChain(SheetWriteHandler handler) {
this.handler = handler;
}
public void beforeSheetCreate(SheetWriteHandlerContext context) {
this.handler.beforeSheetCreate(context);
if (this.next != null) {
this.next.beforeSheetCreate(context);
}
}
public void afterSheetCreate(SheetWriteHandlerContext context) {
this.handler.afterSheetCreate(context);
if (this.next != null) {
this.next.afterSheetCreate(context);
}
}
public void addLast(SheetWriteHandler handler) {
SheetHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new SheetHandlerExecutionChain(handler);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/WorkbookHandlerExecutionChain.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/WorkbookHandlerExecutionChain.java | package com.alibaba.excel.write.handler.chain;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the workbook handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class WorkbookHandlerExecutionChain {
/**
* next chain
*/
private WorkbookHandlerExecutionChain next;
/**
* handler
*/
private WorkbookWriteHandler handler;
public WorkbookHandlerExecutionChain(WorkbookWriteHandler handler) {
this.handler = handler;
}
public void beforeWorkbookCreate(WorkbookWriteHandlerContext context) {
this.handler.beforeWorkbookCreate(context);
if (this.next != null) {
this.next.beforeWorkbookCreate(context);
}
}
public void afterWorkbookCreate(WorkbookWriteHandlerContext context) {
this.handler.afterWorkbookCreate(context);
if (this.next != null) {
this.next.afterWorkbookCreate(context);
}
}
public void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
this.handler.afterWorkbookDispose(context);
if (this.next != null) {
this.next.afterWorkbookDispose(context);
}
}
public void addLast(WorkbookWriteHandler handler) {
WorkbookHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new WorkbookHandlerExecutionChain(handler);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/RowHandlerExecutionChain.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/RowHandlerExecutionChain.java | package com.alibaba.excel.write.handler.chain;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the row handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class RowHandlerExecutionChain {
/**
* next chain
*/
private RowHandlerExecutionChain next;
/**
* handler
*/
private RowWriteHandler handler;
public RowHandlerExecutionChain(RowWriteHandler handler) {
this.handler = handler;
}
public void beforeRowCreate(RowWriteHandlerContext context) {
this.handler.beforeRowCreate(context);
if (this.next != null) {
this.next.beforeRowCreate(context);
}
}
public void afterRowCreate(RowWriteHandlerContext context) {
this.handler.afterRowCreate(context);
if (this.next != null) {
this.next.afterRowCreate(context);
}
}
public void afterRowDispose(RowWriteHandlerContext context) {
this.handler.afterRowDispose(context);
if (this.next != null) {
this.next.afterRowDispose(context);
}
}
public void addLast(RowWriteHandler handler) {
RowHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new RowHandlerExecutionChain(handler);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/CellHandlerExecutionChain.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/chain/CellHandlerExecutionChain.java | package com.alibaba.excel.write.handler.chain;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the cell handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CellHandlerExecutionChain {
/**
* next chain
*/
private CellHandlerExecutionChain next;
/**
* handler
*/
private CellWriteHandler handler;
public CellHandlerExecutionChain(CellWriteHandler handler) {
this.handler = handler;
}
public void beforeCellCreate(CellWriteHandlerContext context) {
this.handler.beforeCellCreate(context);
if (this.next != null) {
this.next.beforeCellCreate(context);
}
}
public void afterCellCreate(CellWriteHandlerContext context) {
this.handler.afterCellCreate(context);
if (this.next != null) {
this.next.afterCellCreate(context);
}
}
public void afterCellDataConverted(CellWriteHandlerContext context) {
this.handler.afterCellDataConverted(context);
if (this.next != null) {
this.next.afterCellDataConverted(context);
}
}
public void afterCellDispose(CellWriteHandlerContext context) {
this.handler.afterCellDispose(context);
if (this.next != null) {
this.next.afterCellDispose(context);
}
}
public void addLast(CellWriteHandler handler) {
CellHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new CellHandlerExecutionChain(handler);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java | package com.alibaba.excel.write.handler.impl;
import java.lang.reflect.Field;
import java.util.Map;
import com.alibaba.excel.util.FieldUtils;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
/**
* Handle the problem of unable to write dimension.
*
* https://github.com/alibaba/easyexcel/issues/1282
*
* @author Jiaju Zhuang
*/
@Slf4j
public class DimensionWorkbookWriteHandler implements WorkbookWriteHandler {
private static final String XSSF_SHEET_MEMBER_VARIABLE_NAME = "_sh";
private static final Field XSSF_SHEET_FIELD = FieldUtils.getField(SXSSFSheet.class, XSSF_SHEET_MEMBER_VARIABLE_NAME,
true);
@Override
public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {
if (writeWorkbookHolder == null || writeWorkbookHolder.getWorkbook() == null) {
return;
}
if (!(writeWorkbookHolder.getWorkbook() instanceof SXSSFWorkbook)) {
return;
}
Map<Integer, WriteSheetHolder> writeSheetHolderMap = writeWorkbookHolder.getHasBeenInitializedSheetIndexMap();
if (MapUtils.isEmpty(writeSheetHolderMap)) {
return;
}
for (WriteSheetHolder writeSheetHolder : writeSheetHolderMap.values()) {
if (writeSheetHolder.getSheet() == null || !(writeSheetHolder.getSheet() instanceof SXSSFSheet)) {
continue;
}
SXSSFSheet sxssfSheet = ((SXSSFSheet)writeSheetHolder.getSheet());
XSSFSheet xssfSheet;
try {
xssfSheet = (XSSFSheet)XSSF_SHEET_FIELD.get(sxssfSheet);
} catch (IllegalAccessException e) {
log.debug("Can not found _sh.", e);
continue;
}
if (xssfSheet == null) {
continue;
}
CTWorksheet ctWorksheet = xssfSheet.getCTWorksheet();
if (ctWorksheet == null) {
continue;
}
int headSize = 0;
if (MapUtils.isNotEmpty(writeSheetHolder.getExcelWriteHeadProperty().getHeadMap())) {
headSize = writeSheetHolder.getExcelWriteHeadProperty().getHeadMap().size();
if (headSize > 0) {
headSize--;
}
}
Integer lastRowIndex = writeSheetHolder.getLastRowIndex();
if (lastRowIndex == null) {
lastRowIndex = 0;
}
ctWorksheet.getDimension().setRef(
"A1:" + CellReference.convertNumToColString(headSize) + (lastRowIndex + 1));
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java | package com.alibaba.excel.write.handler.impl;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
/**
* Default row handler.
*
* @author Jiaju Zhuang
*/
@Slf4j
public class DefaultRowWriteHandler implements RowWriteHandler {
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
context.getWriteSheetHolder().setLastRowIndex(context.getRowIndex());
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/impl/FillStyleCellWriteHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/impl/FillStyleCellWriteHandler.java | package com.alibaba.excel.write.handler.impl;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
/**
* fill cell style.
*
* @author Jiaju Zhuang
*/
@Slf4j
public class FillStyleCellWriteHandler implements CellWriteHandler {
@Override
public int order() {
return OrderConstant.FILL_STYLE;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (BooleanUtils.isTrue(context.getIgnoreFillStyle())) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
if (cellData == null) {
return;
}
WriteCellStyle writeCellStyle = cellData.getWriteCellStyle();
CellStyle originCellStyle = cellData.getOriginCellStyle();
if (writeCellStyle == null && originCellStyle == null) {
return;
}
WriteWorkbookHolder writeWorkbookHolder = context.getWriteWorkbookHolder();
context.getCell().setCellStyle(writeWorkbookHolder.createCellStyle(writeCellStyle, originCellStyle));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/RowWriteHandlerContext.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/RowWriteHandlerContext.java | package com.alibaba.excel.write.handler.context;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.Row;
/**
* row context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public class RowWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
/**
* table .Nullable.It is null without using table writes.
*/
private WriteTableHolder writeTableHolder;
/**
* row index
*/
private Integer rowIndex;
/**
* row
*/
private Row row;
/**
* Nullable.It is null in the case of fill data.
*/
private Integer relativeRowIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Boolean head;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/SheetWriteHandlerContext.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/SheetWriteHandlerContext.java | package com.alibaba.excel.write.handler.context;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* sheet context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public class SheetWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/CellWriteHandlerContext.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/CellWriteHandlerContext.java | package com.alibaba.excel.write.handler.context;
import java.util.List;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.handler.impl.FillStyleCellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* cell context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CellWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
/**
* table .Nullable.It is null without using table writes.
*/
private WriteTableHolder writeTableHolder;
/**
* row
*/
private Row row;
/**
* index
*/
private Integer rowIndex;
/**
* cell
*/
private Cell cell;
/**
* index
*/
private Integer columnIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Integer relativeRowIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Head headData;
/**
* Nullable.It is null in the case of add header.There may be several when fill the data.
*/
private List<WriteCellData<?>> cellDataList;
/**
* Nullable.
* It is null in the case of add header.
* In the case of write there must be not null.
* firstCellData == cellDataList.get(0)
*/
private WriteCellData<?> firstCellData;
/**
* Nullable.It is null in the case of fill data.
*/
private Boolean head;
/**
* Field annotation configuration information.
*/
private ExcelContentProperty excelContentProperty;
/**
* The value of the original
*/
private Object originalValue;
/**
* The original field type
*/
private Class<?> originalFieldClass;
/**
* Target cell data type
*/
private CellDataTypeEnum targetCellDataType;
/**
* Ignore the filling pattern and the {@code FillStyleCellWriteHandler} will not work.
*
* @see FillStyleCellWriteHandler
*/
private Boolean ignoreFillStyle;
public CellWriteHandlerContext(WriteContext writeContext,
WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder,
WriteTableHolder writeTableHolder, Row row, Integer rowIndex, Cell cell, Integer columnIndex,
Integer relativeRowIndex, Head headData, List<WriteCellData<?>> cellDataList, WriteCellData<?> firstCellData,
Boolean head, ExcelContentProperty excelContentProperty) {
this.writeContext = writeContext;
this.writeWorkbookHolder = writeWorkbookHolder;
this.writeSheetHolder = writeSheetHolder;
this.writeTableHolder = writeTableHolder;
this.row = row;
this.rowIndex = rowIndex;
this.cell = cell;
this.columnIndex = columnIndex;
this.relativeRowIndex = relativeRowIndex;
this.headData = headData;
this.cellDataList = cellDataList;
this.firstCellData = firstCellData;
this.head = head;
this.excelContentProperty = excelContentProperty;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/WorkbookWriteHandlerContext.java | easyexcel-core/src/main/java/com/alibaba/excel/write/handler/context/WorkbookWriteHandlerContext.java | package com.alibaba.excel.write.handler.context;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* workbook context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public class WorkbookWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/merge/OnceAbsoluteMergeStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/merge/OnceAbsoluteMergeStrategy.java | package com.alibaba.excel.write.merge;
import org.apache.poi.ss.util.CellRangeAddress;
import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* It only merges once when create cell(firstRowIndex,lastRowIndex)
*
* @author Jiaju Zhuang
*/
public class OnceAbsoluteMergeStrategy implements SheetWriteHandler {
/**
* First row
*/
private final int firstRowIndex;
/**
* Last row
*/
private final int lastRowIndex;
/**
* First column
*/
private final int firstColumnIndex;
/**
* Last row
*/
private final int lastColumnIndex;
public OnceAbsoluteMergeStrategy(int firstRowIndex, int lastRowIndex, int firstColumnIndex, int lastColumnIndex) {
if (firstRowIndex < 0 || lastRowIndex < 0 || firstColumnIndex < 0 || lastColumnIndex < 0) {
throw new IllegalArgumentException("All parameters must be greater than 0");
}
this.firstRowIndex = firstRowIndex;
this.lastRowIndex = lastRowIndex;
this.firstColumnIndex = firstColumnIndex;
this.lastColumnIndex = lastColumnIndex;
}
public OnceAbsoluteMergeStrategy(OnceAbsoluteMergeProperty onceAbsoluteMergeProperty) {
this(onceAbsoluteMergeProperty.getFirstRowIndex(), onceAbsoluteMergeProperty.getLastRowIndex(),
onceAbsoluteMergeProperty.getFirstColumnIndex(), onceAbsoluteMergeProperty.getLastColumnIndex());
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
CellRangeAddress cellRangeAddress =
new CellRangeAddress(firstRowIndex, lastRowIndex, firstColumnIndex, lastColumnIndex);
writeSheetHolder.getSheet().addMergedRegionUnsafe(cellRangeAddress);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java | package com.alibaba.excel.write.merge;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
/**
* Merge strategy
*
* @author Jiaju Zhuang
*/
public abstract class AbstractMergeStrategy implements CellWriteHandler {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (context.getHead()) {
return;
}
merge(context.getWriteSheetHolder().getSheet(), context.getCell(), context.getHeadData(),
context.getRelativeRowIndex());
}
/**
* merge
*
* @param sheet
* @param cell
* @param head
* @param relativeRowIndex
*/
protected abstract void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex);
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java | easyexcel-core/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java | package com.alibaba.excel.write.merge;
import com.alibaba.excel.metadata.property.LoopMergeProperty;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import org.apache.poi.ss.util.CellRangeAddress;
/**
* The regions of the loop merge
*
* @author Jiaju Zhuang
*/
public class LoopMergeStrategy implements RowWriteHandler {
/**
* Each row
*/
private final int eachRow;
/**
* Extend column
*/
private final int columnExtend;
/**
* The number of the current column
*/
private final int columnIndex;
public LoopMergeStrategy(int eachRow, int columnIndex) {
this(eachRow, 1, columnIndex);
}
public LoopMergeStrategy(int eachRow, int columnExtend, int columnIndex) {
if (eachRow < 1) {
throw new IllegalArgumentException("EachRows must be greater than 1");
}
if (columnExtend < 1) {
throw new IllegalArgumentException("ColumnExtend must be greater than 1");
}
if (columnExtend == 1 && eachRow == 1) {
throw new IllegalArgumentException("ColumnExtend or eachRows must be greater than 1");
}
if (columnIndex < 0) {
throw new IllegalArgumentException("ColumnIndex must be greater than 0");
}
this.eachRow = eachRow;
this.columnExtend = columnExtend;
this.columnIndex = columnIndex;
}
public LoopMergeStrategy(LoopMergeProperty loopMergeProperty, Integer columnIndex) {
this(loopMergeProperty.getEachRow(), loopMergeProperty.getColumnExtend(), columnIndex);
}
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
if (context.getHead() || context.getRelativeRowIndex() == null) {
return;
}
if (context.getRelativeRowIndex() % eachRow == 0) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(context.getRowIndex(),
context.getRowIndex() + eachRow - 1,
columnIndex, columnIndex + columnExtend - 1);
context.getWriteSheetHolder().getSheet().addMergedRegionUnsafe(cellRangeAddress);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java | package com.alibaba.excel.analysis;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.metadata.ReadSheet;
/**
* Excel file analyser
*
* @author jipengfei
*/
public interface ExcelAnalyser {
/**
* parse the sheet
*
* @param readSheetList
* Which sheets you need to read.
* @param readAll
* The <code>readSheetList</code> parameter is ignored, and all sheets are read.
*/
void analysis(List<ReadSheet> readSheetList, Boolean readAll);
/**
* Complete the entire read file.Release the cache and close stream
*/
void finish();
/**
* Acquisition excel executor
*
* @return Excel file Executor
*/
ExcelReadExecutor excelExecutor();
/**
* get the analysis context.
*
* @return analysis context
*/
AnalysisContext analysisContext();
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/ExcelReadExecutor.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/ExcelReadExecutor.java | package com.alibaba.excel.analysis;
import java.util.List;
import com.alibaba.excel.read.metadata.ReadSheet;
/**
* Excel file Executor
*
* @author Jiaju Zhuang
*/
public interface ExcelReadExecutor {
/**
* Returns the actual sheet in excel
*
* @return Actual sheet in excel
*/
List<ReadSheet> sheetList();
/**
* Read the sheet.
*/
void execute();
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java | package com.alibaba.excel.analysis;
import com.alibaba.excel.analysis.csv.CsvExcelReadExecutor;
import com.alibaba.excel.analysis.v03.XlsSaxAnalyser;
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.context.csv.CsvReadContext;
import com.alibaba.excel.context.csv.DefaultCsvReadContext;
import com.alibaba.excel.context.xls.DefaultXlsReadContext;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.context.xlsx.DefaultXlsxReadContext;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.ClassUtils;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.NumberDataFormatterUtils;
import com.alibaba.excel.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.List;
/**
* @author jipengfei
*/
public class ExcelAnalyserImpl implements ExcelAnalyser {
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelAnalyserImpl.class);
private AnalysisContext analysisContext;
private ExcelReadExecutor excelReadExecutor;
/**
* Prevent multiple shutdowns
*/
private boolean finished = false;
public ExcelAnalyserImpl(ReadWorkbook readWorkbook) {
try {
choiceExcelExecutor(readWorkbook);
} catch (RuntimeException e) {
finish();
throw e;
} catch (Throwable e) {
finish();
throw new ExcelAnalysisException(e);
}
}
private void choiceExcelExecutor(ReadWorkbook readWorkbook) throws Exception {
ExcelTypeEnum excelType = ExcelTypeEnum.valueOf(readWorkbook);
switch (excelType) {
case XLS:
POIFSFileSystem poifsFileSystem;
if (readWorkbook.getFile() != null) {
poifsFileSystem = new POIFSFileSystem(readWorkbook.getFile());
} else {
poifsFileSystem = new POIFSFileSystem(readWorkbook.getInputStream());
}
// So in encrypted excel, it looks like XLS but it's actually XLSX
if (poifsFileSystem.getRoot().hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) {
InputStream decryptedStream = null;
try {
decryptedStream = DocumentFactoryHelper
.getDecryptedStream(poifsFileSystem.getRoot().getFileSystem(), readWorkbook.getPassword());
XlsxReadContext xlsxReadContext = new DefaultXlsxReadContext(readWorkbook, ExcelTypeEnum.XLSX);
analysisContext = xlsxReadContext;
excelReadExecutor = new XlsxSaxAnalyser(xlsxReadContext, decryptedStream);
return;
} finally {
IOUtils.closeQuietly(decryptedStream);
// as we processed the full stream already, we can close the filesystem here
// otherwise file handles are leaked
poifsFileSystem.close();
}
}
if (readWorkbook.getPassword() != null) {
Biff8EncryptionKey.setCurrentUserPassword(readWorkbook.getPassword());
}
XlsReadContext xlsReadContext = new DefaultXlsReadContext(readWorkbook, ExcelTypeEnum.XLS);
xlsReadContext.xlsReadWorkbookHolder().setPoifsFileSystem(poifsFileSystem);
analysisContext = xlsReadContext;
excelReadExecutor = new XlsSaxAnalyser(xlsReadContext);
break;
case XLSX:
XlsxReadContext xlsxReadContext = new DefaultXlsxReadContext(readWorkbook, ExcelTypeEnum.XLSX);
analysisContext = xlsxReadContext;
excelReadExecutor = new XlsxSaxAnalyser(xlsxReadContext, null);
break;
case CSV:
CsvReadContext csvReadContext = new DefaultCsvReadContext(readWorkbook, ExcelTypeEnum.CSV);
analysisContext = csvReadContext;
excelReadExecutor = new CsvExcelReadExecutor(csvReadContext);
break;
default:
break;
}
}
@Override
public void analysis(List<ReadSheet> readSheetList, Boolean readAll) {
try {
if (!readAll && CollectionUtils.isEmpty(readSheetList)) {
throw new IllegalArgumentException("Specify at least one read sheet.");
}
analysisContext.readWorkbookHolder().setParameterSheetDataList(readSheetList);
analysisContext.readWorkbookHolder().setReadAll(readAll);
try {
excelReadExecutor.execute();
} catch (ExcelAnalysisStopException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Custom stop!");
}
}
} catch (RuntimeException e) {
finish();
throw e;
} catch (Throwable e) {
finish();
throw new ExcelAnalysisException(e);
}
}
@Override
public void finish() {
if (finished) {
return;
}
finished = true;
if (analysisContext == null || analysisContext.readWorkbookHolder() == null) {
return;
}
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
Throwable throwable = null;
try {
if (readWorkbookHolder.getReadCache() != null) {
readWorkbookHolder.getReadCache().destroy();
}
} catch (Throwable t) {
throwable = t;
}
try {
if ((readWorkbookHolder instanceof XlsxReadWorkbookHolder)
&& ((XlsxReadWorkbookHolder) readWorkbookHolder).getOpcPackage() != null) {
((XlsxReadWorkbookHolder) readWorkbookHolder).getOpcPackage().revert();
}
} catch (Throwable t) {
throwable = t;
}
try {
if ((readWorkbookHolder instanceof XlsReadWorkbookHolder)
&& ((XlsReadWorkbookHolder) readWorkbookHolder).getPoifsFileSystem() != null) {
((XlsReadWorkbookHolder) readWorkbookHolder).getPoifsFileSystem().close();
}
} catch (Throwable t) {
throwable = t;
}
// close csv.
// https://github.com/alibaba/easyexcel/issues/2309
try {
if ((readWorkbookHolder instanceof CsvReadWorkbookHolder)
&& ((CsvReadWorkbookHolder) readWorkbookHolder).getCsvParser() != null
&& analysisContext.readWorkbookHolder().getAutoCloseStream()) {
((CsvReadWorkbookHolder) readWorkbookHolder).getCsvParser().close();
}
} catch (Throwable t) {
throwable = t;
}
try {
if (analysisContext.readWorkbookHolder().getAutoCloseStream()
&& readWorkbookHolder.getInputStream() != null) {
readWorkbookHolder.getInputStream().close();
}
} catch (Throwable t) {
throwable = t;
}
try {
if (readWorkbookHolder.getTempFile() != null) {
FileUtils.delete(readWorkbookHolder.getTempFile());
}
} catch (Throwable t) {
throwable = t;
}
clearEncrypt03();
removeThreadLocalCache();
if (throwable != null) {
throw new ExcelAnalysisException("Can not close IO.", throwable);
}
}
private void removeThreadLocalCache() {
NumberDataFormatterUtils.removeThreadLocalCache();
DateUtils.removeThreadLocalCache();
ClassUtils.removeThreadLocalCache();
}
private void clearEncrypt03() {
if (StringUtils.isEmpty(analysisContext.readWorkbookHolder().getPassword())
|| !ExcelTypeEnum.XLS.equals(analysisContext.readWorkbookHolder().getExcelType())) {
return;
}
Biff8EncryptionKey.setCurrentUserPassword(null);
}
@Override
public ExcelReadExecutor excelExecutor() {
return excelReadExecutor;
}
@Override
public AnalysisContext analysisContext() {
return analysisContext;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java | package com.alibaba.excel.analysis.v07;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.analysis.v07.handlers.sax.SharedStringsTableHandler;
import com.alibaba.excel.analysis.v07.handlers.sax.XlsxRowHandler;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.exception.ExcelAnalysisStopSheetException;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.util.SheetUtils;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.Comments;
import org.apache.poi.xssf.model.CommentsTable;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author jipengfei
*/
@Slf4j
public class XlsxSaxAnalyser implements ExcelReadExecutor {
/**
* Storage sheet SharedStrings
*/
public static final PackagePartName SHARED_STRINGS_PART_NAME;
static {
try {
SHARED_STRINGS_PART_NAME = PackagingURIHelper.createPartName("/xl/sharedStrings.xml");
} catch (InvalidFormatException e) {
log.error("Initialize the XlsxSaxAnalyser failure", e);
throw new ExcelAnalysisException("Initialize the XlsxSaxAnalyser failure", e);
}
}
private final XlsxReadContext xlsxReadContext;
private final List<ReadSheet> sheetList;
private final Map<Integer, InputStream> sheetMap;
/**
* excel comments key: sheetNo value: CommentsTable
*/
private final Map<Integer, CommentsTable> commentsTableMap;
public XlsxSaxAnalyser(XlsxReadContext xlsxReadContext, InputStream decryptedStream) throws Exception {
this.xlsxReadContext = xlsxReadContext;
// Initialize cache
XlsxReadWorkbookHolder xlsxReadWorkbookHolder = xlsxReadContext.xlsxReadWorkbookHolder();
OPCPackage pkg = readOpcPackage(xlsxReadWorkbookHolder, decryptedStream);
xlsxReadWorkbookHolder.setOpcPackage(pkg);
// Read the Shared information Strings
PackagePart sharedStringsTablePackagePart = pkg.getPart(SHARED_STRINGS_PART_NAME);
if (sharedStringsTablePackagePart != null) {
// Specify default cache
defaultReadCache(xlsxReadWorkbookHolder, sharedStringsTablePackagePart);
// Analysis sharedStringsTable.xml
analysisSharedStringsTable(sharedStringsTablePackagePart.getInputStream(), xlsxReadWorkbookHolder);
}
XSSFReader xssfReader = new XSSFReader(pkg);
analysisUse1904WindowDate(xssfReader, xlsxReadWorkbookHolder);
// set style table
setStylesTable(xlsxReadWorkbookHolder, xssfReader);
sheetList = new ArrayList<>();
sheetMap = new HashMap<>();
commentsTableMap = new HashMap<>();
Map<Integer, PackageRelationshipCollection> packageRelationshipCollectionMap = MapUtils.newHashMap();
xlsxReadWorkbookHolder.setPackageRelationshipCollectionMap(packageRelationshipCollectionMap);
XSSFReader.SheetIterator ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData();
int index = 0;
if (!ite.hasNext()) {
throw new ExcelAnalysisException("Can not find any sheet!");
}
while (ite.hasNext()) {
InputStream inputStream = ite.next();
sheetList.add(new ReadSheet(index, ite.getSheetName()));
sheetMap.put(index, inputStream);
if (xlsxReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.COMMENT)) {
Comments comments = ite.getSheetComments();
if (comments instanceof CommentsTable) {
commentsTableMap.put(index, (CommentsTable) comments);
}
}
if (xlsxReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.HYPERLINK)) {
PackageRelationshipCollection packageRelationshipCollection = Optional.ofNullable(ite.getSheetPart())
.map(packagePart -> {
try {
return packagePart.getRelationships();
} catch (InvalidFormatException e) {
log.warn("Reading the Relationship failed", e);
return null;
}
}).orElse(null);
if (packageRelationshipCollection != null) {
packageRelationshipCollectionMap.put(index, packageRelationshipCollection);
}
}
index++;
}
}
private void setStylesTable(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, XSSFReader xssfReader) {
try {
xlsxReadWorkbookHolder.setStylesTable(xssfReader.getStylesTable());
} catch (Exception e) {
log.warn(
"Currently excel cannot get style information, but it doesn't affect the data analysis.You can try to"
+ " save the file with office again or ignore the current error.",
e);
}
}
private void defaultReadCache(XlsxReadWorkbookHolder xlsxReadWorkbookHolder,
PackagePart sharedStringsTablePackagePart) {
ReadCache readCache = xlsxReadWorkbookHolder.getReadCacheSelector().readCache(sharedStringsTablePackagePart);
xlsxReadWorkbookHolder.setReadCache(readCache);
readCache.init(xlsxReadContext);
}
private void analysisUse1904WindowDate(XSSFReader xssfReader, XlsxReadWorkbookHolder xlsxReadWorkbookHolder)
throws Exception {
if (xlsxReadWorkbookHolder.globalConfiguration().getUse1904windowing() != null) {
return;
}
InputStream workbookXml = xssfReader.getWorkbookData();
WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);
CTWorkbook wb = ctWorkbook.getWorkbook();
CTWorkbookPr prefix = wb.getWorkbookPr();
if (prefix != null && prefix.getDate1904()) {
xlsxReadWorkbookHolder.getGlobalConfiguration().setUse1904windowing(Boolean.TRUE);
} else {
xlsxReadWorkbookHolder.getGlobalConfiguration().setUse1904windowing(Boolean.FALSE);
}
}
private void analysisSharedStringsTable(InputStream sharedStringsTableInputStream,
XlsxReadWorkbookHolder xlsxReadWorkbookHolder) {
ContentHandler handler = new SharedStringsTableHandler(xlsxReadWorkbookHolder.getReadCache());
parseXmlSource(sharedStringsTableInputStream, handler);
xlsxReadWorkbookHolder.getReadCache().putFinished();
}
private OPCPackage readOpcPackage(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, InputStream decryptedStream)
throws Exception {
if (decryptedStream == null && xlsxReadWorkbookHolder.getFile() != null) {
return OPCPackage.open(xlsxReadWorkbookHolder.getFile());
}
if (xlsxReadWorkbookHolder.getMandatoryUseInputStream()) {
if (decryptedStream != null) {
return OPCPackage.open(decryptedStream);
} else {
return OPCPackage.open(xlsxReadWorkbookHolder.getInputStream());
}
}
File readTempFile = FileUtils.createCacheTmpFile();
xlsxReadWorkbookHolder.setTempFile(readTempFile);
File tempFile = new File(readTempFile.getPath(), UUID.randomUUID() + ".xlsx");
if (decryptedStream != null) {
FileUtils.writeToFile(tempFile, decryptedStream, false);
} else {
FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream(),
xlsxReadWorkbookHolder.getAutoCloseStream());
}
return OPCPackage.open(tempFile, PackageAccess.READ);
}
@Override
public List<ReadSheet> sheetList() {
return sheetList;
}
private void parseXmlSource(InputStream inputStream, ContentHandler handler) {
InputSource inputSource = new InputSource(inputStream);
try {
SAXParserFactory saxFactory;
String xlsxSAXParserFactoryName = xlsxReadContext.xlsxReadWorkbookHolder().getSaxParserFactoryName();
if (StringUtils.isEmpty(xlsxSAXParserFactoryName)) {
saxFactory = SAXParserFactory.newInstance();
} else {
saxFactory = SAXParserFactory.newInstance(xlsxSAXParserFactoryName, null);
}
try {
saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (Throwable ignore) {}
try {
saxFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
} catch (Throwable ignore) {}
try {
saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (Throwable ignore) {}
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(inputSource);
inputStream.close();
} catch (IOException | ParserConfigurationException | SAXException e) {
throw new ExcelAnalysisException(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new ExcelAnalysisException("Can not close 'inputStream'!");
}
}
}
}
@Override
public void execute() {
for (ReadSheet readSheet : sheetList) {
readSheet = SheetUtils.match(readSheet, xlsxReadContext);
if (readSheet != null) {
try {
xlsxReadContext.currentSheet(readSheet);
parseXmlSource(sheetMap.get(readSheet.getSheetNo()), new XlsxRowHandler(xlsxReadContext));
// Read comments
readComments(readSheet);
} catch (ExcelAnalysisStopSheetException e) {
if (log.isDebugEnabled()) {
log.debug("Custom stop!", e);
}
}
// The last sheet is read
xlsxReadContext.analysisEventProcessor().endSheet(xlsxReadContext);
}
}
}
private void readComments(ReadSheet readSheet) {
if (!xlsxReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.COMMENT)) {
return;
}
CommentsTable commentsTable = commentsTableMap.get(readSheet.getSheetNo());
if (commentsTable == null) {
return;
}
Iterator<CellAddress> cellAddresses = commentsTable.getCellAddresses();
while (cellAddresses.hasNext()) {
CellAddress cellAddress = cellAddresses.next();
XSSFComment cellComment = commentsTable.findCellComment(cellAddress);
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, cellComment.getString().toString(),
cellAddress.getRow(), cellAddress.getColumn());
xlsxReadContext.readSheetHolder().setCellExtra(cellExtra);
xlsxReadContext.analysisEventProcessor().extra(xlsxReadContext);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.metadata.data.FormulaData;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import org.xml.sax.Attributes;
/**
* Cell Handler
*
* @author jipengfei
*/
public class CellFormulaTagHandler extends AbstractXlsxTagHandler {
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
xlsxReadSheetHolder.setTempFormula(new StringBuilder());
}
@Override
public void endElement(XlsxReadContext xlsxReadContext, String name) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
FormulaData formulaData = new FormulaData();
formulaData.setFormulaValue(xlsxReadSheetHolder.getTempFormula().toString());
xlsxReadSheetHolder.getTempCellData().setFormulaData(formulaData);
}
@Override
public void characters(XlsxReadContext xlsxReadContext, char[] ch, int start, int length) {
xlsxReadContext.xlsxReadSheetHolder().getTempFormula().append(ch, start, length);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/HyperlinkTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/HyperlinkTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import java.util.Optional;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.xml.sax.Attributes;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.util.StringUtils;
/**
* Cell Handler
*
* @author Jiaju Zhuang
*/
public class HyperlinkTagHandler extends AbstractXlsxTagHandler {
@Override
public boolean support(XlsxReadContext xlsxReadContext) {
return xlsxReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.HYPERLINK);
}
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
String ref = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_REF);
if (StringUtils.isEmpty(ref)) {
return;
}
// Hyperlink has 2 case:
// case 1,In the 'location' tag
String location = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_LOCATION);
if (location != null) {
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.HYPERLINK, location, ref);
xlsxReadContext.readSheetHolder().setCellExtra(cellExtra);
xlsxReadContext.analysisEventProcessor().extra(xlsxReadContext);
return;
}
// case 2, In the 'r:id' tag, Then go to 'PackageRelationshipCollection' to get inside
String rId = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_RID);
PackageRelationshipCollection packageRelationshipCollection = xlsxReadContext.xlsxReadSheetHolder()
.getPackageRelationshipCollection();
if (rId == null || packageRelationshipCollection == null) {
return;
}
Optional.ofNullable(packageRelationshipCollection.getRelationshipByID(rId))
.map(PackageRelationship::getTargetURI)
.ifPresent(uri -> {
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.HYPERLINK, uri.toString(), ref);
xlsxReadContext.readSheetHolder().setCellExtra(cellExtra);
xlsxReadContext.analysisEventProcessor().extra(xlsxReadContext);
});
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
/**
* Cell Value Handler
*
* @author jipengfei
*/
public class CellValueTagHandler extends AbstractCellValueTagHandler {
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/XlsxTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/XlsxTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import org.xml.sax.Attributes;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
/**
* Tag handler
*
* @author Dan Zheng
*/
public interface XlsxTagHandler {
/**
* Whether to support
*
* @param xlsxReadContext
* @return
*/
boolean support(XlsxReadContext xlsxReadContext);
/**
* Start handle
*
* @param xlsxReadContext
* xlsxReadContext
* @param name
* Tag name
* @param attributes
* Tag attributes
*/
void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes);
/**
* End handle
*
* @param xlsxReadContext
* xlsxReadContext
* @param name
* Tag name
*/
void endElement(XlsxReadContext xlsxReadContext, String name);
/**
* Read data
*
* @param xlsxReadContext
* @param ch
* @param start
* @param length
*/
void characters(XlsxReadContext xlsxReadContext, char[] ch, int start, int length);
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import java.math.BigDecimal;
import com.alibaba.excel.constant.EasyExcelConstants;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.PositionUtils;
import com.alibaba.excel.util.StringUtils;
import org.xml.sax.Attributes;
/**
* Cell Handler
*
* @author jipengfei
*/
public class CellTagHandler extends AbstractXlsxTagHandler {
private static final int DEFAULT_FORMAT_INDEX = 0;
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
xlsxReadSheetHolder.setColumnIndex(PositionUtils.getCol(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_R),
xlsxReadSheetHolder.getColumnIndex()));
// t="s" ,it means String
// t="str" ,it means String,but does not need to be read in the 'sharedStrings.xml'
// t="inlineStr" ,it means String,but does not need to be read in the 'sharedStrings.xml'
// t="b" ,it means Boolean
// t="e" ,it means Error
// t="n" ,it means Number
// t is null ,it means Empty or Number
CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_T));
xlsxReadSheetHolder.setTempCellData(new ReadCellData<>(type));
xlsxReadSheetHolder.setTempData(new StringBuilder());
// Put in data transformation information
String dateFormatIndex = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_S);
int dateFormatIndexInteger;
if (StringUtils.isEmpty(dateFormatIndex)) {
dateFormatIndexInteger = DEFAULT_FORMAT_INDEX;
} else {
dateFormatIndexInteger = Integer.parseInt(dateFormatIndex);
}
xlsxReadSheetHolder.getTempCellData().setDataFormatData(
xlsxReadContext.xlsxReadWorkbookHolder().dataFormatData(dateFormatIndexInteger));
}
@Override
public void endElement(XlsxReadContext xlsxReadContext, String name) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
ReadCellData<?> tempCellData = xlsxReadSheetHolder.getTempCellData();
StringBuilder tempData = xlsxReadSheetHolder.getTempData();
String tempDataString = tempData.toString();
CellDataTypeEnum oldType = tempCellData.getType();
switch (oldType) {
case STRING:
// In some cases, although cell type is a string, it may be an empty tag
if (StringUtils.isEmpty(tempDataString)) {
break;
}
String stringValue = xlsxReadContext.readWorkbookHolder().getReadCache().get(
Integer.valueOf(tempDataString));
tempCellData.setStringValue(stringValue);
break;
case DIRECT_STRING:
case ERROR:
tempCellData.setStringValue(tempDataString);
tempCellData.setType(CellDataTypeEnum.STRING);
break;
case BOOLEAN:
if (StringUtils.isEmpty(tempDataString)) {
tempCellData.setType(CellDataTypeEnum.EMPTY);
break;
}
tempCellData.setBooleanValue(BooleanUtils.valueOf(tempData.toString()));
break;
case NUMBER:
case EMPTY:
if (StringUtils.isEmpty(tempDataString)) {
tempCellData.setType(CellDataTypeEnum.EMPTY);
break;
}
tempCellData.setType(CellDataTypeEnum.NUMBER);
tempCellData.setOriginalNumberValue(new BigDecimal(tempDataString));
tempCellData.setNumberValue(
tempCellData.getOriginalNumberValue().round(EasyExcelConstants.EXCEL_MATH_CONTEXT));
break;
default:
throw new IllegalStateException("Cannot set values now");
}
if (tempCellData.getStringValue() != null
&& xlsxReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
tempCellData.setStringValue(tempCellData.getStringValue().trim());
}
tempCellData.checkEmpty();
tempCellData.setRowIndex(xlsxReadSheetHolder.getRowIndex());
tempCellData.setColumnIndex(xlsxReadSheetHolder.getColumnIndex());
xlsxReadSheetHolder.getCellMap().put(xlsxReadSheetHolder.getColumnIndex(), tempCellData);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/MergeCellTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/MergeCellTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import org.xml.sax.Attributes;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.util.StringUtils;
/**
* Cell Handler
*
* @author Jiaju Zhuang
*/
public class MergeCellTagHandler extends AbstractXlsxTagHandler {
@Override
public boolean support(XlsxReadContext xlsxReadContext) {
return xlsxReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.MERGE);
}
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
String ref = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_REF);
if (StringUtils.isEmpty(ref)) {
return;
}
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.MERGE, null, ref);
xlsxReadContext.readSheetHolder().setCellExtra(cellExtra);
xlsxReadContext.analysisEventProcessor().extra(xlsxReadContext);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/RowTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/RowTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import java.util.LinkedHashMap;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.PositionUtils;
import org.apache.commons.collections4.MapUtils;
import org.xml.sax.Attributes;
/**
* Cell Handler
*
* @author jipengfei
*/
public class RowTagHandler extends AbstractXlsxTagHandler {
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
int rowIndex = PositionUtils.getRowByRowTagt(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_R),
xlsxReadSheetHolder.getRowIndex());
Integer lastRowIndex = xlsxReadContext.readSheetHolder().getRowIndex();
while (lastRowIndex + 1 < rowIndex) {
xlsxReadContext.readRowHolder(new ReadRowHolder(lastRowIndex + 1, RowTypeEnum.EMPTY,
xlsxReadSheetHolder.getGlobalConfiguration(), new LinkedHashMap<Integer, Cell>()));
xlsxReadContext.analysisEventProcessor().endRow(xlsxReadContext);
xlsxReadSheetHolder.setColumnIndex(null);
xlsxReadSheetHolder.setCellMap(new LinkedHashMap<Integer, Cell>());
lastRowIndex++;
}
xlsxReadSheetHolder.setRowIndex(rowIndex);
}
@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<>());
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
/**
* Cell inline string value handler
*
* @author jipengfei
*/
public class CellInlineStringValueTagHandler extends AbstractCellValueTagHandler {
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractXlsxTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractXlsxTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import org.xml.sax.Attributes;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
/**
* Abstract tag handler
*
* @author Jiaju Zhuang
*/
public abstract class AbstractXlsxTagHandler implements XlsxTagHandler {
@Override
public boolean support(XlsxReadContext xlsxReadContext) {
return true;
}
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
}
@Override
public void endElement(XlsxReadContext xlsxReadContext, String name) {
}
@Override
public void characters(XlsxReadContext xlsxReadContext, char[] ch, int start, int length) {
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
/**
* Cell Value Handler
*
* @author jipengfei
*/
public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler {
@Override
public void characters(XlsxReadContext xlsxReadContext, char[] ch, int start, int length) {
xlsxReadContext.xlsxReadSheetHolder().getTempData().append(ch, start, length);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CountTagHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/CountTagHandler.java | package com.alibaba.excel.analysis.v07.handlers;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.util.PositionUtils;
import org.xml.sax.Attributes;
/**
* Cell Handler
*
* @author jipengfei
*/
public class CountTagHandler extends AbstractXlsxTagHandler {
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
String d = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_REF);
String totalStr = d.substring(d.indexOf(":") + 1);
xlsxReadContext.readSheetHolder().setApproximateTotalRowNumber(PositionUtils.getRow(totalStr) + 1);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/sax/XlsxRowHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/sax/XlsxRowHandler.java | package com.alibaba.excel.analysis.v07.handlers.sax;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.excel.analysis.v07.handlers.CellFormulaTagHandler;
import com.alibaba.excel.analysis.v07.handlers.CellInlineStringValueTagHandler;
import com.alibaba.excel.analysis.v07.handlers.CellTagHandler;
import com.alibaba.excel.analysis.v07.handlers.CellValueTagHandler;
import com.alibaba.excel.analysis.v07.handlers.CountTagHandler;
import com.alibaba.excel.analysis.v07.handlers.HyperlinkTagHandler;
import com.alibaba.excel.analysis.v07.handlers.MergeCellTagHandler;
import com.alibaba.excel.analysis.v07.handlers.RowTagHandler;
import com.alibaba.excel.analysis.v07.handlers.XlsxTagHandler;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import lombok.extern.slf4j.Slf4j;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author jipengfei
*/
@Slf4j
public class XlsxRowHandler extends DefaultHandler {
private final XlsxReadContext xlsxReadContext;
private static final Map<String, XlsxTagHandler> XLSX_CELL_HANDLER_MAP = new HashMap<>(64);
static {
CellFormulaTagHandler cellFormulaTagHandler = new CellFormulaTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.CELL_FORMULA_TAG, cellFormulaTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_CELL_FORMULA_TAG, cellFormulaTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_CELL_FORMULA_TAG, cellFormulaTagHandler);
CellInlineStringValueTagHandler cellInlineStringValueTagHandler = new CellInlineStringValueTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.CELL_INLINE_STRING_VALUE_TAG, cellInlineStringValueTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_CELL_INLINE_STRING_VALUE_TAG, cellInlineStringValueTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_CELL_INLINE_STRING_VALUE_TAG, cellInlineStringValueTagHandler);
CellTagHandler cellTagHandler = new CellTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.CELL_TAG, cellTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_CELL_TAG, cellTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_CELL_TAG, cellTagHandler);
CellValueTagHandler cellValueTagHandler = new CellValueTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.CELL_VALUE_TAG, cellValueTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_CELL_VALUE_TAG, cellValueTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_CELL_VALUE_TAG, cellValueTagHandler);
CountTagHandler countTagHandler = new CountTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.DIMENSION_TAG, countTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_DIMENSION_TAG, countTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_DIMENSION_TAG, countTagHandler);
HyperlinkTagHandler hyperlinkTagHandler = new HyperlinkTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.HYPERLINK_TAG, hyperlinkTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_HYPERLINK_TAG, hyperlinkTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_HYPERLINK_TAG, hyperlinkTagHandler);
MergeCellTagHandler mergeCellTagHandler = new MergeCellTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.MERGE_CELL_TAG, mergeCellTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_MERGE_CELL_TAG, mergeCellTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_MERGE_CELL_TAG, mergeCellTagHandler);
RowTagHandler rowTagHandler = new RowTagHandler();
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.ROW_TAG, rowTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.X_ROW_TAG, rowTagHandler);
XLSX_CELL_HANDLER_MAP.put(ExcelXmlConstants.NS2_ROW_TAG, rowTagHandler);
}
public XlsxRowHandler(XlsxReadContext xlsxReadContext) {
this.xlsxReadContext = xlsxReadContext;
}
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
XlsxTagHandler handler = XLSX_CELL_HANDLER_MAP.get(name);
if (handler == null || !handler.support(xlsxReadContext)) {
return;
}
xlsxReadContext.xlsxReadSheetHolder().getTagDeque().push(name);
handler.startElement(xlsxReadContext, name, attributes);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String currentTag = xlsxReadContext.xlsxReadSheetHolder().getTagDeque().peek();
if (currentTag == null) {
return;
}
XlsxTagHandler handler = XLSX_CELL_HANDLER_MAP.get(currentTag);
if (handler == null || !handler.support(xlsxReadContext)) {
return;
}
handler.characters(xlsxReadContext, ch, start, length);
}
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
XlsxTagHandler handler = XLSX_CELL_HANDLER_MAP.get(name);
if (handler == null || !handler.support(xlsxReadContext)) {
return;
}
handler.endElement(xlsxReadContext, name);
xlsxReadContext.xlsxReadSheetHolder().getTagDeque().pop();
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/sax/SharedStringsTableHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v07/handlers/sax/SharedStringsTableHandler.java | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package com.alibaba.excel.analysis.v07.handlers.sax;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.constant.ExcelXmlConstants;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
/**
* Sax read sharedStringsTable.xml
*
* @author Jiaju Zhuang
*/
public class SharedStringsTableHandler extends DefaultHandler {
private static final Pattern UTF_PATTTERN = Pattern.compile("_x([0-9A-Fa-f]{4})_");
/**
* The final piece of data
*/
private StringBuilder currentData;
/**
* Current element data
*/
private StringBuilder currentElementData;
private final ReadCache readCache;
/**
* Some fields in the T tag need to be ignored
*/
private boolean ignoreTagt = false;
/**
* The only time you need to read the characters in the T tag is when it is used
*/
private boolean isTagt = false;
public SharedStringsTableHandler(ReadCache readCache) {
this.readCache = readCache;
}
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) {
if (name == null) {
return;
}
switch (name) {
case ExcelXmlConstants.SHAREDSTRINGS_T_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_X_T_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_NS2_T_TAG:
currentElementData = null;
isTagt = true;
break;
case ExcelXmlConstants.SHAREDSTRINGS_SI_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_X_SI_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_NS2_SI_TAG:
currentData = null;
break;
case ExcelXmlConstants.SHAREDSTRINGS_RPH_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_X_RPH_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_NS2_RPH_TAG:
ignoreTagt = true;
break;
default:
// ignore
}
}
@Override
public void endElement(String uri, String localName, String name) {
if (name == null) {
return;
}
switch (name) {
case ExcelXmlConstants.SHAREDSTRINGS_T_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_X_T_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_NS2_T_TAG:
if (currentElementData != null) {
if (currentData == null) {
currentData = new StringBuilder();
}
currentData.append(currentElementData);
}
isTagt = false;
break;
case ExcelXmlConstants.SHAREDSTRINGS_SI_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_X_SI_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_NS2_SI_TAG:
if (currentData == null) {
readCache.put(null);
} else {
readCache.put(utfDecode(currentData.toString()));
}
break;
case ExcelXmlConstants.SHAREDSTRINGS_RPH_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_X_RPH_TAG:
case ExcelXmlConstants.SHAREDSTRINGS_NS2_RPH_TAG:
ignoreTagt = false;
break;
default:
// ignore
}
}
@Override
public void characters(char[] ch, int start, int length) {
if (!isTagt || ignoreTagt) {
return;
}
if (currentElementData == null) {
currentElementData = new StringBuilder();
}
currentElementData.append(ch, start, length);
}
/**
* from poi XSSFRichTextString
*
* @param value the string to decode
* @return the decoded string or null if the input string is null
* <p>
* For all characters which cannot be represented in XML as defined by the XML 1.0 specification,
* the characters are escaped using the Unicode numerical character representation escape character
* format _xHHHH_, where H represents a hexadecimal character in the character's value.
* <p>
* Example: The Unicode character 0D is invalid in an XML 1.0 document,
* so it shall be escaped as <code>_x000D_</code>.
* </p>
* See section 3.18.9 in the OOXML spec.
* @see org.apache.poi.xssf.usermodel.XSSFRichTextString#utfDecode(String)
*/
static String utfDecode(String value) {
if (value == null || !value.contains("_x")) {
return value;
}
StringBuilder buf = new StringBuilder();
Matcher m = UTF_PATTTERN.matcher(value);
int idx = 0;
while (m.find()) {
int pos = m.start();
if (pos > idx) {
buf.append(value, idx, pos);
}
String code = m.group(1);
int icode = Integer.decode("0x" + code);
buf.append((char)icode);
idx = m.end();
}
// small optimization: don't go via StringBuilder if not necessary,
// the encodings are very rare, so we should almost always go via this shortcut.
if (idx == 0) {
return value;
}
buf.append(value.substring(idx));
return buf.toString();
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java | package com.alibaba.excel.analysis.csv;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.context.csv.CsvReadContext;
import com.alibaba.excel.enums.ByteOrderMarkEnum;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.exception.ExcelAnalysisStopSheetException;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder;
import com.alibaba.excel.util.SheetUtils;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.input.BOMInputStream;
/**
* read executor
*
* @author zhuangjiaju
*/
@Slf4j
public class CsvExcelReadExecutor implements ExcelReadExecutor {
private final List<ReadSheet> sheetList;
private final CsvReadContext csvReadContext;
public CsvExcelReadExecutor(CsvReadContext csvReadContext) {
this.csvReadContext = csvReadContext;
sheetList = new ArrayList<>();
ReadSheet readSheet = new ReadSheet();
sheetList.add(readSheet);
readSheet.setSheetNo(0);
}
@Override
public List<ReadSheet> sheetList() {
return sheetList;
}
@Override
public void execute() {
CSVParser csvParser;
try {
csvParser = csvParser();
csvReadContext.csvReadWorkbookHolder().setCsvParser(csvParser);
} catch (IOException e) {
throw new ExcelAnalysisException(e);
}
for (ReadSheet readSheet : sheetList) {
readSheet = SheetUtils.match(readSheet, csvReadContext);
if (readSheet == null) {
continue;
}
try {
csvReadContext.currentSheet(readSheet);
int rowIndex = 0;
for (CSVRecord record : csvParser) {
dealRecord(record, rowIndex++);
}
} catch (ExcelAnalysisStopSheetException e) {
if (log.isDebugEnabled()) {
log.debug("Custom stop!", e);
}
}
// The last sheet is read
csvReadContext.analysisEventProcessor().endSheet(csvReadContext);
}
}
private CSVParser csvParser() throws IOException {
CsvReadWorkbookHolder csvReadWorkbookHolder = csvReadContext.csvReadWorkbookHolder();
CSVFormat csvFormat = csvReadWorkbookHolder.getCsvFormat();
ByteOrderMarkEnum byteOrderMark = ByteOrderMarkEnum.valueOfByCharsetName(
csvReadContext.csvReadWorkbookHolder().getCharset().name());
if (csvReadWorkbookHolder.getMandatoryUseInputStream()) {
return buildCsvParser(csvFormat, csvReadWorkbookHolder.getInputStream(), byteOrderMark);
}
if (csvReadWorkbookHolder.getFile() != null) {
return buildCsvParser(csvFormat, Files.newInputStream(csvReadWorkbookHolder.getFile().toPath()),
byteOrderMark);
}
return buildCsvParser(csvFormat, csvReadWorkbookHolder.getInputStream(), byteOrderMark);
}
private CSVParser buildCsvParser(CSVFormat csvFormat, InputStream inputStream, ByteOrderMarkEnum byteOrderMark)
throws IOException {
if (byteOrderMark == null) {
return csvFormat.parse(
new InputStreamReader(inputStream, csvReadContext.csvReadWorkbookHolder().getCharset()));
}
return csvFormat.parse(new InputStreamReader(new BOMInputStream(inputStream, byteOrderMark.getByteOrderMark()),
csvReadContext.csvReadWorkbookHolder().getCharset()));
}
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);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java | package com.alibaba.excel.analysis.v03;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.EOFRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.HyperlinkRecord;
import org.apache.poi.hssf.record.IndexRecord;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.MergeCellsRecord;
import org.apache.poi.hssf.record.NoteRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.RKRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.record.TextObjectRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.analysis.v03.handlers.BlankRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.BofRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.BoolErrRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.BoundSheetRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.DummyRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.EofRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.FormulaRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.HyperlinkRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.IndexRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.LabelRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.LabelSstRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.MergeCellsRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.NoteRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.NumberRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.ObjRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.RkRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.SstRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.StringRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.TextObjectRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.exception.ExcelAnalysisStopSheetException;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder;
/**
* A text extractor for Excel files.
* <p>
* Returns the textual content of the file, suitable for indexing by something like Lucene, but not really intended for
* display to the user.
* </p>
*
* <p>
* To turn an excel file into a CSV or similar, then see the XLS2CSVmra example
* </p>
*
*
* @author jipengfei
* @see <a href="http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java">XLS2CSVmra</a>
*/
@Slf4j
public class XlsSaxAnalyser implements HSSFListener, ExcelReadExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(XlsSaxAnalyser.class);
private static final short DUMMY_RECORD_SID = -1;
private final XlsReadContext xlsReadContext;
private static final Map<Short, XlsRecordHandler> XLS_RECORD_HANDLER_MAP = new HashMap<Short, XlsRecordHandler>(32);
static {
XLS_RECORD_HANDLER_MAP.put(BlankRecord.sid, new BlankRecordHandler());
XLS_RECORD_HANDLER_MAP.put(BOFRecord.sid, new BofRecordHandler());
XLS_RECORD_HANDLER_MAP.put(BoolErrRecord.sid, new BoolErrRecordHandler());
XLS_RECORD_HANDLER_MAP.put(BoundSheetRecord.sid, new BoundSheetRecordHandler());
XLS_RECORD_HANDLER_MAP.put(DUMMY_RECORD_SID, new DummyRecordHandler());
XLS_RECORD_HANDLER_MAP.put(EOFRecord.sid, new EofRecordHandler());
XLS_RECORD_HANDLER_MAP.put(FormulaRecord.sid, new FormulaRecordHandler());
XLS_RECORD_HANDLER_MAP.put(HyperlinkRecord.sid, new HyperlinkRecordHandler());
XLS_RECORD_HANDLER_MAP.put(IndexRecord.sid, new IndexRecordHandler());
XLS_RECORD_HANDLER_MAP.put(LabelRecord.sid, new LabelRecordHandler());
XLS_RECORD_HANDLER_MAP.put(LabelSSTRecord.sid, new LabelSstRecordHandler());
XLS_RECORD_HANDLER_MAP.put(MergeCellsRecord.sid, new MergeCellsRecordHandler());
XLS_RECORD_HANDLER_MAP.put(NoteRecord.sid, new NoteRecordHandler());
XLS_RECORD_HANDLER_MAP.put(NumberRecord.sid, new NumberRecordHandler());
XLS_RECORD_HANDLER_MAP.put(ObjRecord.sid, new ObjRecordHandler());
XLS_RECORD_HANDLER_MAP.put(RKRecord.sid, new RkRecordHandler());
XLS_RECORD_HANDLER_MAP.put(SSTRecord.sid, new SstRecordHandler());
XLS_RECORD_HANDLER_MAP.put(StringRecord.sid, new StringRecordHandler());
XLS_RECORD_HANDLER_MAP.put(TextObjectRecord.sid, new TextObjectRecordHandler());
}
public XlsSaxAnalyser(XlsReadContext xlsReadContext) {
this.xlsReadContext = xlsReadContext;
}
@Override
public List<ReadSheet> sheetList() {
try {
if (xlsReadContext.readWorkbookHolder().getActualSheetDataList() == null) {
new XlsListSheetListener(xlsReadContext).execute();
}
} catch (ExcelAnalysisStopException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Custom stop!");
}
}
return xlsReadContext.readWorkbookHolder().getActualSheetDataList();
}
@Override
public void execute() {
XlsReadWorkbookHolder xlsReadWorkbookHolder = xlsReadContext.xlsReadWorkbookHolder();
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
xlsReadWorkbookHolder.setFormatTrackingHSSFListener(new FormatTrackingHSSFListener(listener));
EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener =
new EventWorkbookBuilder.SheetRecordCollectingListener(
xlsReadWorkbookHolder.getFormatTrackingHSSFListener());
xlsReadWorkbookHolder.setHssfWorkbook(workbookBuildingListener.getStubHSSFWorkbook());
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
request.addListenerForAllRecords(xlsReadWorkbookHolder.getFormatTrackingHSSFListener());
try {
factory.processWorkbookEvents(request, xlsReadWorkbookHolder.getPoifsFileSystem());
} catch (IOException e) {
throw new ExcelAnalysisException(e);
}
// There are some special xls that do not have the terminator "[EOF]", so an additional
xlsReadContext.analysisEventProcessor().endSheet(xlsReadContext);
}
@Override
public void processRecord(Record record) {
XlsRecordHandler handler = XLS_RECORD_HANDLER_MAP.get(record.getSid());
if (handler == null) {
return;
}
boolean ignoreRecord =
(handler instanceof IgnorableXlsRecordHandler) && xlsReadContext.xlsReadWorkbookHolder().getIgnoreRecord();
if (ignoreRecord) {
// No need to read the current sheet
return;
}
if (!handler.support(xlsReadContext, record)) {
return;
}
try {
handler.processRecord(xlsReadContext, record);
} catch (ExcelAnalysisStopSheetException e) {
if (log.isDebugEnabled()) {
log.debug("Custom stop!", e);
}
xlsReadContext.xlsReadWorkbookHolder().setIgnoreRecord(Boolean.TRUE);
xlsReadContext.xlsReadWorkbookHolder().setCurrentSheetStopped(Boolean.TRUE);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/IgnorableXlsRecordHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/IgnorableXlsRecordHandler.java | package com.alibaba.excel.analysis.v03;
/**
* Need to ignore the current handler without reading the current sheet.
*
* @author Jiaju Zhuang
*/
public interface IgnorableXlsRecordHandler extends XlsRecordHandler {}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/XlsListSheetListener.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/XlsListSheetListener.java | package com.alibaba.excel.analysis.v03;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.handlers.BofRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.BoundSheetRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
/**
* In some cases, you need to know the number of sheets in advance and only read the file once in advance.
*
* @author Jiaju Zhuang
*/
public class XlsListSheetListener implements HSSFListener {
private final XlsReadContext xlsReadContext;
private static final Map<Short, XlsRecordHandler> XLS_RECORD_HANDLER_MAP = new HashMap<Short, XlsRecordHandler>();
static {
XLS_RECORD_HANDLER_MAP.put(BOFRecord.sid, new BofRecordHandler());
XLS_RECORD_HANDLER_MAP.put(BoundSheetRecord.sid, new BoundSheetRecordHandler());
}
public XlsListSheetListener(XlsReadContext xlsReadContext) {
this.xlsReadContext = xlsReadContext;
xlsReadContext.xlsReadWorkbookHolder().setNeedReadSheet(Boolean.FALSE);
}
@Override
public void processRecord(Record record) {
XlsRecordHandler handler = XLS_RECORD_HANDLER_MAP.get(record.getSid());
if (handler == null) {
return;
}
handler.processRecord(xlsReadContext, record);
}
public void execute() {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
HSSFListener formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener =
new EventWorkbookBuilder.SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
try {
factory.processWorkbookEvents(request, xlsReadContext.xlsReadWorkbookHolder().getPoifsFileSystem());
} catch (IOException e) {
throw new ExcelAnalysisException(e);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/XlsRecordHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/XlsRecordHandler.java | package com.alibaba.excel.analysis.v03;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.context.xls.XlsReadContext;
/**
* Intercepts handle xls reads.
*
* @author Dan Zheng
*/
public interface XlsRecordHandler {
/**
* Whether to support
*
* @param xlsReadContext
* @param record
* @return
*/
boolean support(XlsReadContext xlsReadContext, Record record);
/**
* Processing record
*
* @param xlsReadContext
* @param record
*/
void processRecord(XlsReadContext xlsReadContext, Record record);
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/handlers/HyperlinkRecordHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/handlers/HyperlinkRecordHandler.java | package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.HyperlinkRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.metadata.CellExtra;
/**
* Record handler
*
* @author Dan Zheng
*/
public class HyperlinkRecordHandler extends AbstractXlsRecordHandler implements IgnorableXlsRecordHandler {
@Override
public boolean support(XlsReadContext xlsReadContext, Record record) {
return xlsReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.HYPERLINK);
}
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
HyperlinkRecord hr = (HyperlinkRecord)record;
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.HYPERLINK, hr.getAddress(), hr.getFirstRow(),
hr.getLastRow(), hr.getFirstColumn(), hr.getLastColumn());
xlsReadContext.xlsReadSheetHolder().setCellExtra(cellExtra);
xlsReadContext.analysisEventProcessor().extra(xlsReadContext);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java | easyexcel-core/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java | package com.alibaba.excel.analysis.v03.handlers;
import java.util.LinkedHashMap;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadSheetHolder;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.record.Record;
/**
* Record handler
*
* @author Dan Zheng
*/
public class DummyRecordHandler extends AbstractXlsRecordHandler implements IgnorableXlsRecordHandler {
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
XlsReadSheetHolder xlsReadSheetHolder = xlsReadContext.xlsReadSheetHolder();
if (record instanceof LastCellOfRowDummyRecord) {
// End of this row
LastCellOfRowDummyRecord lcrdr = (LastCellOfRowDummyRecord)record;
xlsReadSheetHolder.setRowIndex(lcrdr.getRow());
xlsReadContext.readRowHolder(new ReadRowHolder(lcrdr.getRow(), xlsReadSheetHolder.getTempRowType(),
xlsReadContext.readSheetHolder().getGlobalConfiguration(), xlsReadSheetHolder.getCellMap()));
xlsReadContext.analysisEventProcessor().endRow(xlsReadContext);
xlsReadSheetHolder.setCellMap(new LinkedHashMap<Integer, Cell>());
xlsReadSheetHolder.setTempRowType(RowTypeEnum.EMPTY);
} else if (record instanceof MissingCellDummyRecord) {
MissingCellDummyRecord mcdr = (MissingCellDummyRecord)record;
// https://github.com/alibaba/easyexcel/issues/2236
// Some abnormal XLS, in the case of data already exist, or there will be a "MissingCellDummyRecord"
// records, so if the existing data, empty data is ignored
xlsReadSheetHolder.getCellMap().putIfAbsent(mcdr.getColumn(),
ReadCellData.newEmptyInstance(mcdr.getRow(), mcdr.getColumn()));
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.