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-test/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsDataTest.java | package com.alibaba.easyexcel.test.core.multiplesheets;
import java.io.File;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class MultipleSheetsDataTest {
private static File file07;
private static File file03;
@BeforeAll
public static void init() {
file07 = TestFileUtil.readFile("multiplesheets" + File.separator + "multiplesheets.xlsx");
file03 = TestFileUtil.readFile("multiplesheets" + File.separator + "multiplesheets.xls");
}
@Test
public void t01Read07() {
read(file07);
}
@Test
public void t02Read03() {
read(file03);
}
@Test
public void t03Read07All() {
readAll(file07);
}
@Test
public void t04Read03All() {
readAll(file03);
}
private void read(File file) {
MultipleSheetsListener multipleSheetsListener = new MultipleSheetsListener();
try (ExcelReader excelReader = EasyExcel.read(file, MultipleSheetsData.class, multipleSheetsListener).build()) {
List<ReadSheet> sheets = excelReader.excelExecutor().sheetList();
int count = 1;
for (ReadSheet readSheet : sheets) {
excelReader.read(readSheet);
Assertions.assertEquals(multipleSheetsListener.getList().size(), count);
count++;
}
}
}
private void readAll(File file) {
EasyExcel.read(file, MultipleSheetsData.class, new MultipleSheetsListener()).doReadAll();
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsListener.java | package com.alibaba.easyexcel.test.core.multiplesheets;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class MultipleSheetsListener extends AnalysisEventListener<MultipleSheetsData> {
private static final Logger LOGGER = LoggerFactory.getLogger(MultipleSheetsListener.class);
List<MultipleSheetsData> list = new ArrayList<MultipleSheetsData>();
@Override
public void invoke(MultipleSheetsData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
LOGGER.debug("A form is read finished.");
Assertions.assertEquals(list.get(0).getTitle(), "表1数据");
LOGGER.debug("All row:{}", JSON.toJSONString(list));
}
public List<MultipleSheetsData> getList() {
return list;
}
public void setList(List<MultipleSheetsData> list) {
this.list = list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsData.java | package com.alibaba.easyexcel.test.core.multiplesheets;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class MultipleSheetsData {
private String title;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java | package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class ReadAllConverterDataListener extends AnalysisEventListener<ReadAllConverterData> {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadAllConverterDataListener.class);
List<ReadAllConverterData> list = new ArrayList<ReadAllConverterData>();
@Override
public void invoke(ReadAllConverterData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 1);
ReadAllConverterData data = list.get(0);
Assertions.assertEquals(data.getBigDecimalBoolean().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0);
Assertions.assertEquals(data.getBigDecimalNumber().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0);
Assertions.assertEquals(data.getBigDecimalString().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0);
Assertions.assertEquals(data.getBigIntegerBoolean().intValue(), BigInteger.ONE.intValue(), 0.0);
Assertions.assertEquals(data.getBigIntegerNumber().intValue(), BigInteger.ONE.intValue(), 0.0);
Assertions.assertEquals(data.getBigIntegerString().intValue(), BigInteger.ONE.intValue(), 0.0);
Assertions.assertTrue(data.getBooleanBoolean());
Assertions.assertTrue(data.getBooleanNumber());
Assertions.assertTrue(data.getBooleanString());
Assertions.assertEquals((long)data.getByteBoolean(), 1L);
Assertions.assertEquals((long)data.getByteNumber(), 1L);
Assertions.assertEquals((long)data.getByteString(), 1L);
try {
Assertions.assertEquals(data.getDateNumber(), DateUtils.parseDate("2020-01-01 01:01:01"));
Assertions.assertEquals(data.getDateString(), DateUtils.parseDate("2020-01-01 01:01:01"));
} catch (ParseException e) {
throw new ExcelCommonException("Test Exception", e);
}
Assertions.assertEquals(data.getLocalDateTimeNumber(),
DateUtils.parseLocalDateTime("2020-01-01 01:01:01", null, null));
Assertions.assertEquals(data.getLocalDateTimeString(),
DateUtils.parseLocalDateTime("2020-01-01 01:01:01", null, null));
Assertions.assertEquals(data.getDoubleBoolean(), 1.0, 0.0);
Assertions.assertEquals(data.getDoubleNumber(), 1.0, 0.0);
Assertions.assertEquals(data.getDoubleString(), 1.0, 0.0);
Assertions.assertEquals(data.getFloatBoolean(), (float)1.0, 0.0);
Assertions.assertEquals(data.getFloatNumber(), (float)1.0, 0.0);
Assertions.assertEquals(data.getFloatString(), (float)1.0, 0.0);
Assertions.assertEquals((long)data.getIntegerBoolean(), 1L);
Assertions.assertEquals((long)data.getIntegerNumber(), 1L);
Assertions.assertEquals((long)data.getIntegerString(), 1L);
Assertions.assertEquals((long)data.getLongBoolean(), 1L);
Assertions.assertEquals((long)data.getLongNumber(), 1L);
Assertions.assertEquals((long)data.getLongString(), 1L);
Assertions.assertEquals((long)data.getShortBoolean(), 1L);
Assertions.assertEquals((long)data.getShortNumber(), 1L);
Assertions.assertEquals((long)data.getShortString(), 1L);
Assertions.assertEquals(data.getStringBoolean().toLowerCase(), "true");
Assertions.assertEquals(data.getStringString(), "测试");
Assertions.assertEquals(data.getStringError(), "#VALUE!");
if (context.readWorkbookHolder().getExcelType() != ExcelTypeEnum.CSV) {
Assertions.assertEquals("2020-1-1 1:01", data.getStringNumberDate());
} else {
Assertions.assertEquals("2020-01-01 01:01:01", data.getStringNumberDate());
}
double doubleStringFormulaNumber = new BigDecimal(data.getStringFormulaNumber()).doubleValue();
Assertions.assertEquals(doubleStringFormulaNumber, 2.0, 0.0);
Assertions.assertEquals(data.getStringFormulaString(), "1测试");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java | package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class ConverterDataListener extends AnalysisEventListener<ConverterReadData> {
private static final Logger LOGGER = LoggerFactory.getLogger(ConverterDataListener.class);
private final List<ConverterReadData> list = new ArrayList<>();
@Override
public void invoke(ConverterReadData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 1);
ConverterReadData data = list.get(0);
Assertions.assertEquals(TestUtil.TEST_DATE, data.getDate());
Assertions.assertEquals(TestUtil.TEST_LOCAL_DATE, data.getLocalDate());
Assertions.assertEquals(TestUtil.TEST_LOCAL_DATE_TIME, data.getLocalDateTime());
Assertions.assertEquals(data.getBooleanData(), Boolean.TRUE);
Assertions.assertEquals(data.getBigDecimal().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0);
Assertions.assertEquals(data.getBigInteger().intValue(), BigInteger.ONE.intValue(), 0.0);
Assertions.assertEquals((long)data.getLongData(), 1L);
Assertions.assertEquals((long)data.getIntegerData(), 1L);
Assertions.assertEquals((long)data.getShortData(), 1L);
Assertions.assertEquals((long)data.getByteData(), 1L);
Assertions.assertEquals(data.getDoubleData(), 1.0, 0.0);
Assertions.assertEquals(data.getFloatData(), (float)1.0, 0.0);
Assertions.assertEquals(data.getString(), "测试");
Assertions.assertEquals(data.getCellData().getStringValue(), "自定义");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterData.java | package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.Date;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class ReadAllConverterData {
private BigDecimal bigDecimalBoolean;
private BigDecimal bigDecimalNumber;
private BigDecimal bigDecimalString;
private BigInteger bigIntegerBoolean;
private BigInteger bigIntegerNumber;
private BigInteger bigIntegerString;
private Boolean booleanBoolean;
private Boolean booleanNumber;
private Boolean booleanString;
private Byte byteBoolean;
private Byte byteNumber;
private Byte byteString;
private Date dateNumber;
private Date dateString;
private LocalDateTime localDateTimeNumber;
private LocalDateTime localDateTimeString;
private Double doubleBoolean;
private Double doubleNumber;
private Double doubleString;
private Float floatBoolean;
private Float floatNumber;
private Float floatString;
private Integer integerBoolean;
private Integer integerNumber;
private Integer integerString;
private Long longBoolean;
private Long longNumber;
private Long longString;
private Short shortBoolean;
private Short shortNumber;
private Short shortString;
private String stringBoolean;
private String stringNumber;
private String stringString;
private String stringError;
private String stringFormulaNumber;
private String stringFormulaString;
private String stringNumberDate;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterTest.java | package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.converters.floatconverter.FloatNumberConverter;
import com.alibaba.excel.metadata.data.WriteCellData;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class ConverterTest {
@Test
public void t01FloatNumberConverter() {
FloatNumberConverter floatNumberConverter = new FloatNumberConverter();
WriteConverterContext<Float> context = new WriteConverterContext<>();
context.setValue(95.62F);
WriteCellData<?> writeCellData = floatNumberConverter.convertToExcelData(context);
Assertions.assertEquals(0, writeCellData.getNumberValue().compareTo(new BigDecimal("95.62")));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterWriteData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterWriteData.java | package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.data.WriteCellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class ConverterWriteData {
@ExcelProperty("日期")
private Date date;
@ExcelProperty("本地日期")
private LocalDate localDate;
@ExcelProperty("本地日期时间")
private LocalDateTime localDateTime;
@ExcelProperty("布尔")
private Boolean booleanData;
@ExcelProperty("大数")
private BigDecimal bigDecimal;
@ExcelProperty("大整数")
private BigInteger bigInteger;
@ExcelProperty("长整型")
private long longData;
@ExcelProperty("整型")
private Integer integerData;
@ExcelProperty("短整型")
private Short shortData;
@ExcelProperty("字节型")
private Byte byteData;
@ExcelProperty("双精度浮点型")
private double doubleData;
@ExcelProperty("浮点型")
private Float floatData;
@ExcelProperty("字符串")
private String string;
@ExcelProperty("自定义")
private WriteCellData<?> cellData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ImageData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ImageData.java | package com.alibaba.easyexcel.test.core.converter;
import java.io.File;
import java.io.InputStream;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.converters.string.StringImageConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@ContentRowHeight(500)
@ColumnWidth(500 / 8)
public class ImageData {
private File file;
private InputStream inputStream;
@ExcelProperty(converter = StringImageConverter.class)
private String string;
private byte[] byteArray;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterReadData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterReadData.java | package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.data.ReadCellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class ConverterReadData {
@ExcelProperty("日期")
private Date date;
@ExcelProperty("本地日期")
private LocalDate localDate;
@ExcelProperty("本地日期时间")
private LocalDateTime localDateTime;
@ExcelProperty("布尔")
private Boolean booleanData;
@ExcelProperty("大数")
private BigDecimal bigDecimal;
@ExcelProperty("大整数")
private BigInteger bigInteger;
@ExcelProperty("长整型")
private long longData;
@ExcelProperty("整型")
private Integer integerData;
@ExcelProperty("短整型")
private Short shortData;
@ExcelProperty("字节型")
private Byte byteData;
@ExcelProperty("双精度浮点型")
private double doubleData;
@ExcelProperty("浮点型")
private Float floatData;
@ExcelProperty("字符串")
private String string;
@ExcelProperty("自定义")
private ReadCellData<?> cellData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java | package com.alibaba.easyexcel.test.core.converter;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.easyexcel.test.util.TestUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.FileUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class ConverterDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
private static File fileImage07;
private static File fileImage03;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("converter07.xlsx");
file03 = TestFileUtil.createNewFile("converter03.xls");
fileCsv = TestFileUtil.createNewFile("converterCsv.csv");
fileImage07 = TestFileUtil.createNewFile("converterImage07.xlsx");
fileImage03 = TestFileUtil.createNewFile("converterImage03.xls");
}
@Test
public void t01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteCsv() throws Exception {
readAndWrite(fileCsv);
}
private void readAndWrite(File file) throws Exception {
EasyExcel.write(file, ConverterWriteData.class).sheet().doWrite(data());
EasyExcel.read(file, ConverterReadData.class, new ConverterDataListener()).sheet().doRead();
}
@Test
public void t11ReadAllConverter07() {
readAllConverter("converter" + File.separator + "converter07.xlsx");
}
@Test
public void t12ReadAllConverter03() {
readAllConverter("converter" + File.separator + "converter03.xls");
}
@Test
public void t13ReadAllConverterCsv() {
readAllConverter("converter" + File.separator + "converterCsv.csv");
}
@Test
public void t21WriteImage07() throws Exception {
writeImage(fileImage07);
}
@Test
public void t22WriteImage03() throws Exception {
writeImage(fileImage03);
}
private void writeImage(File file) throws Exception {
InputStream inputStream = null;
try {
List<ImageData> list = new ArrayList<>();
ImageData imageData = new ImageData();
list.add(imageData);
String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg";
imageData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath)));
imageData.setFile(new File(imagePath));
imageData.setString(imagePath);
inputStream = FileUtils.openInputStream(new File(imagePath));
imageData.setInputStream(inputStream);
EasyExcel.write(file, ImageData.class).sheet().doWrite(list);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
private void readAllConverter(String fileName) {
EasyExcel.read(TestFileUtil.readFile(fileName), ReadAllConverterData.class, new ReadAllConverterDataListener())
.sheet().doRead();
}
private List<ConverterWriteData> data() throws Exception {
List<ConverterWriteData> list = new ArrayList<ConverterWriteData>();
ConverterWriteData converterWriteData = new ConverterWriteData();
converterWriteData.setDate(TestUtil.TEST_DATE);
converterWriteData.setLocalDate(TestUtil.TEST_LOCAL_DATE);
converterWriteData.setLocalDateTime(TestUtil.TEST_LOCAL_DATE_TIME);
converterWriteData.setBooleanData(Boolean.TRUE);
converterWriteData.setBigDecimal(BigDecimal.ONE);
converterWriteData.setBigInteger(BigInteger.ONE);
converterWriteData.setLongData(1L);
converterWriteData.setIntegerData(1);
converterWriteData.setShortData((short)1);
converterWriteData.setByteData((byte)1);
converterWriteData.setDoubleData(1.0);
converterWriteData.setFloatData((float)1.0);
converterWriteData.setString("测试");
converterWriteData.setCellData(new WriteCellData<>("自定义"));
list.add(converterWriteData);
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/FillData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/FillData.java | package com.alibaba.easyexcel.test.core.fill;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.converters.doubleconverter.DoubleStringConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class FillData {
private String name;
@NumberFormat("#")
@ExcelProperty(converter = DoubleStringConverter.class)
private Double number;
private String empty;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/FillDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/FillDataTest.java | package com.alibaba.easyexcel.test.core.fill;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class FillDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
private static File simpleTemplate07;
private static File simpleTemplate03;
private static File simpleTemplateCsv;
private static File fileComplex07;
private static File complexFillTemplate07;
private static File fileComplex03;
private static File complexFillTemplate03;
private static File fileHorizontal07;
private static File horizontalFillTemplate07;
private static File fileHorizontal03;
private static File horizontalFillTemplate03;
private static File byName07;
private static File byName03;
private static File byNameTemplate07;
private static File byNameTemplate03;
private static File fileComposite07;
private static File compositeFillTemplate07;
private static File fileComposite03;
private static File compositeFillTemplate03;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("fill07.xlsx");
file03 = TestFileUtil.createNewFile("fill03.xls");
fileCsv = TestFileUtil.createNewFile("fill.csv");
simpleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "simple.xlsx");
simpleTemplate03 = TestFileUtil.readFile("fill" + File.separator + "simple.xls");
simpleTemplateCsv = TestFileUtil.readFile("fill" + File.separator + "simple.csv");
fileComplex07 = TestFileUtil.createNewFile("fillComplex07.xlsx");
complexFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "complex.xlsx");
fileComplex03 = TestFileUtil.createNewFile("fillComplex03.xls");
complexFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "complex.xls");
fileHorizontal07 = TestFileUtil.createNewFile("fillHorizontal07.xlsx");
horizontalFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "horizontal.xlsx");
fileHorizontal03 = TestFileUtil.createNewFile("fillHorizontal03.xls");
horizontalFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "horizontal.xls");
byName07 = TestFileUtil.createNewFile("byName07.xlsx");
byNameTemplate07 = TestFileUtil.readFile("fill" + File.separator + "byName.xlsx");
byName03 = TestFileUtil.createNewFile("byName03.xls");
byNameTemplate03 = TestFileUtil.readFile("fill" + File.separator + "byName.xls");
fileComposite07 = TestFileUtil.createNewFile("fileComposite07.xlsx");
compositeFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "composite.xlsx");
fileComposite03 = TestFileUtil.createNewFile("fileComposite03.xls");
compositeFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "composite.xls");
}
@Test
public void t01Fill07() {
fill(file07, simpleTemplate07);
}
@Test
public void t02Fill03() {
fill(file03, simpleTemplate03);
}
@Test
public void t03FillCsv() {
ExcelGenerateException excelGenerateException = Assertions.assertThrows(ExcelGenerateException.class,
() -> fill(fileCsv, simpleTemplateCsv));
Assertions.assertEquals("csv cannot use template.", excelGenerateException.getMessage());
}
@Test
public void t03ComplexFill07() {
complexFill(fileComplex07, complexFillTemplate07);
}
@Test
public void t04ComplexFill03() {
complexFill(fileComplex03, complexFillTemplate03);
}
@Test
public void t05HorizontalFill07() {
horizontalFill(fileHorizontal07, horizontalFillTemplate07);
}
@Test
public void t06HorizontalFill03() {
horizontalFill(fileHorizontal03, horizontalFillTemplate03);
}
@Test
public void t07ByNameFill07() {
byNameFill(byName07, byNameTemplate07);
}
@Test
public void t08ByNameFill03() {
byNameFill(byName03, byNameTemplate03);
}
@Test
public void t09CompositeFill07() {
compositeFill(fileComposite07, compositeFillTemplate07);
}
@Test
public void t10CompositeFill03() {
compositeFill(fileComposite03, compositeFillTemplate03);
}
private void byNameFill(File file, File template) {
FillData fillData = new FillData();
fillData.setName("张三");
fillData.setNumber(5.2);
EasyExcel.write(file, FillData.class).withTemplate(template).sheet("Sheet2").doFill(fillData);
}
private void compositeFill(File file, File template) {
try (ExcelWriter excelWriter = EasyExcel.write(file).withTemplate(template).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet);
excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet);
excelWriter.fill(new FillWrapper("data2", data()), writeSheet);
excelWriter.fill(new FillWrapper("data2", data()), writeSheet);
excelWriter.fill(new FillWrapper("data3", data()), writeSheet);
excelWriter.fill(new FillWrapper("data3", data()), writeSheet);
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "2019年10月9日13:28:28");
excelWriter.fill(map, writeSheet);
}
List<Object> list = EasyExcel.read(file).ignoreEmptyRow(false).sheet().headRowNumber(0).doReadSync();
Map<String, String> map0 = (Map<String, String>)list.get(0);
Assertions.assertEquals("张三", map0.get(21));
Map<String, String> map27 = (Map<String, String>)list.get(27);
Assertions.assertEquals("张三", map27.get(0));
Map<String, String> map29 = (Map<String, String>)list.get(29);
Assertions.assertEquals("张三", map29.get(3));
}
private void horizontalFill(File file, File template) {
try (ExcelWriter excelWriter = EasyExcel.write(file).withTemplate(template).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
excelWriter.fill(data(), fillConfig, writeSheet);
excelWriter.fill(data(), fillConfig, writeSheet);
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "2019年10月9日13:28:28");
excelWriter.fill(map, writeSheet);
excelWriter.finish();
}
List<Object> list = EasyExcel.read(file).sheet().headRowNumber(0).doReadSync();
Assertions.assertEquals(list.size(), 5L);
Map<String, String> map0 = (Map<String, String>)list.get(0);
Assertions.assertEquals("张三", map0.get(2));
}
private void complexFill(File file, File template) {
try (ExcelWriter excelWriter = EasyExcel.write(file).withTemplate(template).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().registerWriteHandler(new LoopMergeStrategy(2, 0)).build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(data(), fillConfig, writeSheet);
excelWriter.fill(data(), fillConfig, writeSheet);
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "2019年10月9日13:28:28");
map.put("total", 1000);
excelWriter.fill(map, writeSheet);
}
List<Object> list = EasyExcel.read(file).sheet().headRowNumber(3).doReadSync();
Assertions.assertEquals(list.size(), 21L);
Map<String, String> map19 = (Map<String, String>)list.get(19);
Assertions.assertEquals("张三", map19.get(0));
}
private void fill(File file, File template) {
FillData fillData = new FillData();
fillData.setName("张三");
fillData.setNumber(5.2);
EasyExcel.write(file, FillData.class).withTemplate(template).sheet().doFill(fillData);
}
private List<FillData> data() {
List<FillData> list = new ArrayList<FillData>();
for (int i = 0; i < 10; i++) {
FillData fillData = new FillData();
list.add(fillData);
fillData.setName("张三");
fillData.setNumber(5.2);
if (i == 5) {
fillData.setName(null);
}
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleData.java | package com.alibaba.easyexcel.test.core.fill.style;
import java.util.Date;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class FillStyleData {
private String name;
private Double number;
private Date date;
private String empty;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleAnnotatedData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleAnnotatedData.java | package com.alibaba.easyexcel.test.core.fill.style;
import java.util.Date;
import com.alibaba.excel.annotation.write.style.ContentFontStyle;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.enums.BooleanEnum;
import com.alibaba.excel.enums.poi.FillPatternTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class FillStyleAnnotatedData {
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 13)
@ContentFontStyle(bold = BooleanEnum.TRUE, color = 19)
private String name;
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 10)
@ContentFontStyle(bold = BooleanEnum.TRUE, color = 16)
private Double number;
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 17)
@ContentFontStyle(bold = BooleanEnum.TRUE, color = 58)
private Date date;
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 12)
@ContentFontStyle(bold = BooleanEnum.TRUE, color = 18)
private String empty;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleDataTest.java | package com.alibaba.easyexcel.test.core.fill.style;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class FillStyleDataTest {
private static File fileStyle07;
private static File fileStyle03;
private static File fileStyleHandler07;
private static File fileStyleHandler03;
private static File fileStyleTemplate07;
private static File fileStyleTemplate03;
@BeforeAll
public static void init() {
fileStyle07 = TestFileUtil.createNewFile("fileStyle07.xlsx");
fileStyle03 = TestFileUtil.createNewFile("fileStyle03.xls");
fileStyleHandler07 = TestFileUtil.createNewFile("fileStyleHandler07.xlsx");
fileStyleHandler03 = TestFileUtil.createNewFile("fileStyleHandler03.xls");
fileStyleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "style.xlsx");
fileStyleTemplate03 = TestFileUtil.readFile("fill" + File.separator + "style.xls");
}
@Test
public void t01Fill07() throws Exception {
fill(fileStyle07, fileStyleTemplate07);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileStyle07));
XSSFSheet sheet = workbook.getSheetAt(0);
t01Fill07check(sheet.getRow(1));
t01Fill07check(sheet.getRow(2));
}
private void t01Fill07check(XSSFRow row) {
XSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("FF00B050", cell0.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF7030A0", cell0.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell0.getCellStyle().getFont().getBold());
XSSFCell cell1 = row.getCell(1);
Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1);
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("FF92D050", cell1.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF4BACC6", cell1.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertFalse(cell1.getCellStyle().getFont().getBold());
XSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("FFFFC000", cell2.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FFC0504D", cell2.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell2.getCellStyle().getFont().getBold());
XSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5.2岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF0000", cell3.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FFEEECE1", cell3.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell3.getCellStyle().getFont().getBold());
XSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("FFC00000", cell4.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF000000", cell4.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertFalse(cell4.getCellStyle().getFont().getBold());
XSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("FFF79646", cell5.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF8064A2", cell5.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertFalse(cell5.getCellStyle().getFont().getBold());
}
@Test
public void t02Fill03() throws Exception {
fill(fileStyle03, fileStyleTemplate03);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileStyle03));
HSSFSheet sheet = workbook.getSheetAt(0);
t02Fill03check(workbook, sheet.getRow(1));
t02Fill03check(workbook, sheet.getRow(2));
}
private void t02Fill03check(HSSFWorkbook workbook, HSSFRow row) {
HSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("0:8080:0", cell0.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:0:8080", cell0.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell0.getCellStyle().getFont(workbook).getBold());
HSSFCell cell1 = row.getCell(1);
Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1);
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("9999:CCCC:0", cell1.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("0:8080:8080", cell1.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertFalse(cell1.getCellStyle().getFont(workbook).getBold());
HSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("FFFF:CCCC:0", cell2.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:0:0", cell2.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell2.getCellStyle().getFont(workbook).getBold());
HSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5.2岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:0:0", cell3.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("FFFF:FFFF:9999", cell3.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell3.getCellStyle().getFont(workbook).getBold());
HSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("9999:3333:0", cell4.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("3333:3333:3333", cell4.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertFalse(cell4.getCellStyle().getFont(workbook).getBold());
HSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("9999:3333:0", cell5.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("CCCC:9999:FFFF", cell5.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertFalse(cell5.getCellStyle().getFont(workbook).getBold());
}
private void fill(File file, File template) throws Exception {
EasyExcel.write(file, FillStyleData.class).withTemplate(template).sheet().doFill(data());
}
@Test
public void t11FillStyleHandler07() throws Exception {
fillStyleHandler(fileStyleHandler07, fileStyleTemplate07);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileStyleHandler07));
XSSFSheet sheet = workbook.getSheetAt(0);
t11FillStyleHandler07check(sheet.getRow(1));
t11FillStyleHandler07check(sheet.getRow(2));
}
private void t11FillStyleHandler07check(XSSFRow row) {
XSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFFFF00", cell0.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF808000", cell0.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell0.getCellStyle().getFont().getBold());
XSSFCell cell1 = row.getCell(1);
Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1);
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF0000", cell1.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF800000", cell1.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell1.getCellStyle().getFont().getBold());
XSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("FF008000", cell2.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF003300", cell2.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell2.getCellStyle().getFont().getBold());
XSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5.2岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF0000", cell3.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FFEEECE1", cell3.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell3.getCellStyle().getFont().getBold());
XSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("FFC00000", cell4.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF000000", cell4.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertFalse(cell4.getCellStyle().getFont().getBold());
XSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("FFF79646", cell5.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF8064A2", cell5.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertFalse(cell5.getCellStyle().getFont().getBold());
}
@Test
public void t12FillStyleHandler03() throws Exception {
fillStyleHandler(fileStyleHandler03, fileStyleTemplate03);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileStyleHandler03));
HSSFSheet sheet = workbook.getSheetAt(0);
t12FillStyleHandler03check(workbook, sheet.getRow(1));
t12FillStyleHandler03check(workbook, sheet.getRow(2));
}
private void t12FillStyleHandler03check(HSSFWorkbook workbook, HSSFRow row) {
HSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:FFFF:0", cell0.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:8080:0", cell0.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell0.getCellStyle().getFont(workbook).getBold());
HSSFCell cell1 = row.getCell(1);
Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1);
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:0:0", cell1.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:0:0", cell1.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell1.getCellStyle().getFont(workbook).getBold());
HSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("0:8080:0", cell2.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("0:3333:0", cell2.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell2.getCellStyle().getFont(workbook).getBold());
HSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5.2岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:0:0", cell3.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("FFFF:FFFF:9999", cell3.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell3.getCellStyle().getFont(workbook).getBold());
HSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("9999:3333:0", cell4.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("3333:3333:3333", cell4.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertFalse(cell4.getCellStyle().getFont(workbook).getBold());
HSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("9999:3333:0", cell5.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("CCCC:9999:FFFF", cell5.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertFalse(cell5.getCellStyle().getFont(workbook).getBold());
}
private void fillStyleHandler(File file, File template) throws Exception {
EasyExcel.write(file, FillStyleData.class).withTemplate(template).sheet()
.registerWriteHandler(new AbstractVerticalCellStyleStrategy() {
@Override
protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) {
WriteCellStyle writeCellStyle = new WriteCellStyle();
WriteFont writeFont = new WriteFont();
writeCellStyle.setWriteFont(writeFont);
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
writeFont.setBold(true);
if (context.getColumnIndex() == 0) {
writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex());
}
if (context.getColumnIndex() == 1) {
writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
writeFont.setColor(IndexedColors.DARK_RED.getIndex());
}
if (context.getColumnIndex() == 2) {
writeCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
writeFont.setColor(IndexedColors.DARK_GREEN.getIndex());
}
if (context.getColumnIndex() == 3) {
writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
writeFont.setColor(IndexedColors.DARK_BLUE.getIndex());
}
if (context.getColumnIndex() == 4) {
writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex());
}
if (context.getColumnIndex() == 5) {
writeCellStyle.setFillForegroundColor(IndexedColors.TEAL.getIndex());
writeFont.setColor(IndexedColors.DARK_TEAL.getIndex());
}
return writeCellStyle;
}
@Override
protected WriteCellStyle headCellStyle(Head head) {
return null;
}
})
.doFill(data());
}
private List<FillStyleData> data() throws Exception {
List<FillStyleData> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
FillStyleData fillData = new FillStyleData();
list.add(fillData);
fillData.setName("张三");
fillData.setNumber(5.2);
fillData.setDate(DateUtils.parseDate("2020-01-01 01:01:01"));
if (i == 5) {
fillData.setName(null);
}
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleAnnotatedTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/style/FillStyleAnnotatedTest.java | package com.alibaba.easyexcel.test.core.fill.style;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import com.alibaba.easyexcel.test.core.fill.FillData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class FillStyleAnnotatedTest {
private static File FillStyleAnnotated07;
private static File FillStyleAnnotated03;
private static File fileStyleTemplate07;
private static File fileStyleTemplate03;
@BeforeAll
public static void init() {
FillStyleAnnotated07 = TestFileUtil.createNewFile("FillStyleAnnotated07.xlsx");
FillStyleAnnotated03 = TestFileUtil.createNewFile("FillStyleAnnotated03.xls");
fileStyleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "style.xlsx");
fileStyleTemplate03 = TestFileUtil.readFile("fill" + File.separator + "style.xls");
}
@Test
public void t01Fill07() throws Exception {
fill(FillStyleAnnotated07, fileStyleTemplate07);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(FillStyleAnnotated07));
XSSFSheet sheet = workbook.getSheetAt(0);
t01Fill07check(sheet.getRow(1));
t01Fill07check(sheet.getRow(2));
}
private void t01Fill07check(XSSFRow row) {
XSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFFFF00", cell0.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF808000", cell0.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell0.getCellStyle().getFont().getBold());
XSSFCell cell1 = row.getCell(1);
Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1);
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF0000", cell1.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF800000", cell1.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell1.getCellStyle().getFont().getBold());
XSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("FF008000", cell2.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF003300", cell2.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell2.getCellStyle().getFont().getBold());
XSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5.2岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF0000", cell3.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FFEEECE1", cell3.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell3.getCellStyle().getFont().getBold());
XSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("FFC00000", cell4.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF000000", cell4.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertFalse(cell4.getCellStyle().getFont().getBold());
XSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("FFF79646", cell5.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF8064A2", cell5.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertFalse(cell5.getCellStyle().getFont().getBold());
}
@Test
public void t02Fill03() throws Exception {
fill(FillStyleAnnotated03, fileStyleTemplate03);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(FillStyleAnnotated03));
HSSFSheet sheet = workbook.getSheetAt(0);
t02Fill03check(workbook, sheet.getRow(1));
t02Fill03check(workbook, sheet.getRow(2));
}
private void t02Fill03check(HSSFWorkbook workbook, HSSFRow row) {
HSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:FFFF:0", cell0.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:8080:0", cell0.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell0.getCellStyle().getFont(workbook).getBold());
HSSFCell cell1 = row.getCell(1);
Assertions.assertEquals(5.2, cell1.getNumericCellValue(), 1);
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:0:0", cell1.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:0:0", cell1.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell1.getCellStyle().getFont(workbook).getBold());
HSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("0:8080:0", cell2.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("0:3333:0", cell2.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell2.getCellStyle().getFont(workbook).getBold());
HSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5.2岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:0:0", cell3.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("FFFF:FFFF:9999", cell3.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell3.getCellStyle().getFont(workbook).getBold());
HSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("9999:3333:0", cell4.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("3333:3333:3333", cell4.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertFalse(cell4.getCellStyle().getFont(workbook).getBold());
HSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("9999:3333:0", cell5.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("CCCC:9999:FFFF", cell5.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertFalse(cell5.getCellStyle().getFont(workbook).getBold());
}
private void fill(File file, File template) throws Exception {
EasyExcel.write(file, FillStyleAnnotatedData.class).withTemplate(template).sheet().doFill(data());
}
private void t11FillStyleHandler07check(XSSFRow row) {
XSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFFFF00", cell0.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF808000", cell0.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell0.getCellStyle().getFont().getBold());
XSSFCell cell1 = row.getCell(1);
Assertions.assertEquals("5", cell1.getStringCellValue());
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF0000", cell1.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF800000", cell1.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell1.getCellStyle().getFont().getBold());
XSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("FF008000", cell2.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF003300", cell2.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell2.getCellStyle().getFont().getBold());
XSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("FF0000FF", cell3.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF000080", cell3.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell3.getCellStyle().getFont().getBold());
XSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFFFF00", cell4.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF808000", cell4.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell4.getCellStyle().getFont().getBold());
XSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("FF008080", cell5.getCellStyle().getFillForegroundColorColor().getARGBHex());
Assertions.assertEquals("FF003366", cell5.getCellStyle().getFont().getXSSFColor().getARGBHex());
Assertions.assertTrue(cell5.getCellStyle().getFont().getBold());
}
private void t12FillStyleHandler03check(HSSFWorkbook workbook, HSSFRow row) {
HSSFCell cell0 = row.getCell(0);
Assertions.assertEquals("张三", cell0.getStringCellValue());
Assertions.assertEquals(49, cell0.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:FFFF:0", cell0.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:8080:0", cell0.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell0.getCellStyle().getFont(workbook).getBold());
HSSFCell cell1 = row.getCell(1);
Assertions.assertEquals("5", cell1.getStringCellValue());
Assertions.assertEquals(0, cell1.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:0:0", cell1.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:0:0", cell1.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell1.getCellStyle().getFont(workbook).getBold());
HSSFCell cell2 = row.getCell(2);
Assertions.assertEquals("2020-01-01 01:01:01",
DateUtils.format(cell2.getDateCellValue(), "yyyy-MM-dd HH:mm:ss"));
Assertions.assertEquals("yyyy-MM-dd HH:mm:ss", cell2.getCellStyle().getDataFormatString());
Assertions.assertEquals("0:8080:0", cell2.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("0:3333:0", cell2.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell2.getCellStyle().getFont(workbook).getBold());
HSSFCell cell3 = row.getCell(3);
Assertions.assertEquals("张三今年5岁了", cell3.getStringCellValue());
Assertions.assertEquals(0, cell3.getCellStyle().getDataFormat());
Assertions.assertEquals("0:0:FFFF", cell3.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("0:0:8080", cell3.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell3.getCellStyle().getFont(workbook).getBold());
HSSFCell cell4 = row.getCell(4);
Assertions.assertEquals("{.name}忽略,张三", cell4.getStringCellValue());
Assertions.assertEquals(0, cell4.getCellStyle().getDataFormat());
Assertions.assertEquals("FFFF:FFFF:0", cell4.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("8080:8080:0", cell4.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell4.getCellStyle().getFont(workbook).getBold());
HSSFCell cell5 = row.getCell(5);
Assertions.assertEquals("空", cell5.getStringCellValue());
Assertions.assertEquals(0, cell5.getCellStyle().getDataFormat());
Assertions.assertEquals("0:8080:8080", cell5.getCellStyle().getFillForegroundColorColor().getHexString());
Assertions.assertEquals("0:3333:6666", cell5.getCellStyle().getFont(workbook).getHSSFColor(workbook)
.getHexString());
Assertions.assertTrue(cell5.getCellStyle().getFont(workbook).getBold());
}
private void fillStyleHandler(File file, File template) throws Exception {
EasyExcel.write(file, FillData.class).withTemplate(template).sheet()
.registerWriteHandler(new AbstractVerticalCellStyleStrategy() {
@Override
protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) {
WriteCellStyle writeCellStyle = new WriteCellStyle();
WriteFont writeFont = new WriteFont();
writeCellStyle.setWriteFont(writeFont);
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
writeFont.setBold(true);
if (context.getColumnIndex() == 0) {
writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex());
}
if (context.getColumnIndex() == 1) {
writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
writeFont.setColor(IndexedColors.DARK_RED.getIndex());
}
if (context.getColumnIndex() == 2) {
writeCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
writeFont.setColor(IndexedColors.DARK_GREEN.getIndex());
}
if (context.getColumnIndex() == 3) {
writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
writeFont.setColor(IndexedColors.DARK_BLUE.getIndex());
}
if (context.getColumnIndex() == 4) {
writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
writeFont.setColor(IndexedColors.DARK_YELLOW.getIndex());
}
if (context.getColumnIndex() == 5) {
writeCellStyle.setFillForegroundColor(IndexedColors.TEAL.getIndex());
writeFont.setColor(IndexedColors.DARK_TEAL.getIndex());
}
return writeCellStyle;
}
@Override
protected WriteCellStyle headCellStyle(Head head) {
return null;
}
})
.doFill(data());
}
private List<FillStyleAnnotatedData> data() throws Exception {
List<FillStyleAnnotatedData> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
FillStyleAnnotatedData fillData = new FillStyleAnnotatedData();
list.add(fillData);
fillData.setName("张三");
fillData.setNumber(5.2);
fillData.setDate(DateUtils.parseDate("2020-01-01 01:01:01"));
if (i == 5) {
fillData.setName(null);
}
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/annotation/FillAnnotationData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/annotation/FillAnnotationData.java | package com.alibaba.easyexcel.test.core.fill.annotation;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ContentLoopMerge;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.converters.string.StringImageConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@ContentRowHeight(100)
public class FillAnnotationData {
@ExcelProperty("日期")
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
private Date date;
@ExcelProperty(value = "数字")
@NumberFormat("#.##%")
private Double number;
@ContentLoopMerge(columnExtend = 2)
@ExcelProperty("字符串1")
private String string1;
@ExcelProperty("字符串2")
private String string2;
@ExcelProperty(value = "图片", converter = StringImageConverter.class)
private String image;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/annotation/FillAnnotationDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/fill/annotation/FillAnnotationDataTest.java | package com.alibaba.easyexcel.test.core.fill.annotation;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class FillAnnotationDataTest {
private static File file07;
private static File file03;
private static File fileTemplate07;
private static File fileTemplate03;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("fillAnnotation07.xlsx");
file03 = TestFileUtil.createNewFile("fillAnnotation03.xls");
fileTemplate07 = TestFileUtil.readFile("fill" + File.separator + "annotation.xlsx");
fileTemplate03 = TestFileUtil.readFile("fill" + File.separator + "annotation.xls");
}
@Test
public void t01ReadAndWrite07() throws Exception {
readAndWrite(file07, fileTemplate07);
}
@Test
public void t02ReadAndWrite03() throws Exception {
readAndWrite(file03, fileTemplate03);
}
private void readAndWrite(File file, File fileTemplate) throws Exception {
EasyExcel.write().file(file).head(FillAnnotationData.class).withTemplate(fileTemplate).sheet().doFill(data());
try (Workbook workbook = WorkbookFactory.create(file)) {
Sheet sheet = workbook.getSheetAt(0);
Row row1 = sheet.getRow(1);
Assertions.assertEquals(2000, row1.getHeight(), 0);
Cell cell10 = row1.getCell(0);
Date date = cell10.getDateCellValue();
Assertions.assertEquals(DateUtils.parseDate("2020-01-01 01:01:01").getTime(), date.getTime());
String dataFormatString = cell10.getCellStyle().getDataFormatString();
Assertions.assertEquals("yyyy年MM月dd日HH时mm分ss秒", dataFormatString);
Cell cell11 = row1.getCell(1);
Assertions.assertEquals(99.99, cell11.getNumericCellValue(), 2);
boolean hasMerge = false;
for (CellRangeAddress mergedRegion : sheet.getMergedRegions()) {
if (mergedRegion.getFirstRow() == 1 && mergedRegion.getLastRow() == 1
&& mergedRegion.getFirstColumn() == 2 && mergedRegion.getLastColumn() == 3) {
hasMerge = true;
break;
}
}
Assertions.assertTrue(hasMerge);
if (sheet instanceof XSSFSheet) {
XSSFSheet xssfSheet = (XSSFSheet)sheet;
List<XSSFShape> shapeList = xssfSheet.getDrawingPatriarch().getShapes();
XSSFShape shape0 = shapeList.get(0);
Assertions.assertTrue(shape0 instanceof XSSFPicture);
XSSFPicture picture0 = (XSSFPicture)shape0;
CTMarker ctMarker0 = picture0.getPreferredSize().getFrom();
Assertions.assertEquals(1, ctMarker0.getRow());
Assertions.assertEquals(4, ctMarker0.getCol());
} else {
HSSFSheet hssfSheet = (HSSFSheet)sheet;
List<HSSFShape> shapeList = hssfSheet.getDrawingPatriarch().getChildren();
HSSFShape shape0 = shapeList.get(0);
Assertions.assertTrue(shape0 instanceof HSSFPicture);
HSSFPicture picture0 = (HSSFPicture)shape0;
HSSFClientAnchor anchor = (HSSFClientAnchor)picture0.getAnchor();
Assertions.assertEquals(1, anchor.getRow1());
Assertions.assertEquals(4, anchor.getCol1());
}
}
}
private List<FillAnnotationData> data() throws Exception {
List<FillAnnotationData> list = new ArrayList<>();
FillAnnotationData data = new FillAnnotationData();
data.setDate(DateUtils.parseDate("2020-01-01 01:01:01"));
data.setNumber(99.99);
data.setString1("string1");
data.setString2("string2");
data.setImage(TestFileUtil.getPath() + "converter" + File.separator + "img.jpg");
list.add(data);
list.add(data);
list.add(data);
list.add(data);
list.add(data);
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java | package com.alibaba.easyexcel.test.core.annotation;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.core.StyleTestUtils;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class AnnotationDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
private static File fileStyle07;
private static File fileStyle03;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("annotation07.xlsx");
file03 = TestFileUtil.createNewFile("annotation03.xls");
fileStyle07 = TestFileUtil.createNewFile("annotationStyle07.xlsx");
fileStyle03 = TestFileUtil.createNewFile("annotationStyle03.xls");
fileCsv = TestFileUtil.createNewFile("annotationCsv.csv");
}
@Test
public void t01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteCsv() throws Exception {
readAndWrite(fileCsv);
}
@Test
public void t11WriteStyle07() throws Exception {
writeStyle(fileStyle07);
}
@Test
public void t12Write03() throws Exception {
writeStyle(fileStyle03);
}
private void writeStyle(File file) throws Exception {
EasyExcel.write().file(file).head(AnnotationStyleData.class).sheet().doWrite(dataStyle());
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
Row row0 = sheet.getRow(0);
Cell cell00 = row0.getCell(0);
Assertions.assertArrayEquals(new byte[] {-1, 0, -1}, StyleTestUtils.getFillForegroundColor(cell00));
Assertions.assertArrayEquals(new byte[] {-1, -52, 0}, StyleTestUtils.getFontColor(cell00, workbook));
Assertions.assertEquals(40, StyleTestUtils.getFontHeightInPoints(cell00, workbook));
Cell cell01 = row0.getCell(1);
Assertions.assertArrayEquals(new byte[] {-1, 0, 0}, StyleTestUtils.getFillForegroundColor(cell01));
Assertions.assertArrayEquals(new byte[] {0, -1, -1}, StyleTestUtils.getFontColor(cell01, workbook));
Assertions.assertEquals(20, StyleTestUtils.getFontHeightInPoints(cell01, workbook));
Row row1 = sheet.getRow(1);
Cell cell10 = row1.getCell(0);
Assertions.assertArrayEquals(new byte[] {0, -52, -1}, StyleTestUtils.getFillForegroundColor(cell10));
Assertions.assertArrayEquals(new byte[] {0, 0, -1}, StyleTestUtils.getFontColor(cell10, workbook));
Assertions.assertEquals(50, StyleTestUtils.getFontHeightInPoints(cell10, workbook));
Cell cell11 = row1.getCell(1);
Assertions.assertArrayEquals(new byte[] {0, -128, 0}, StyleTestUtils.getFillForegroundColor(cell11));
Assertions.assertArrayEquals(new byte[] {-64, -64, -64}, StyleTestUtils.getFontColor(cell11, workbook));
Assertions.assertEquals(30, StyleTestUtils.getFontHeightInPoints(cell11, workbook));
}
private void readAndWrite(File file) throws Exception {
EasyExcel.write().file(file).head(AnnotationData.class).sheet().doWrite(dataStyle());
if (file == fileCsv) {
return;
}
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
Assertions.assertEquals(50 * 256, sheet.getColumnWidth(0), 0);
Row row0 = sheet.getRow(0);
Assertions.assertEquals(1000, row0.getHeight(), 0);
Row row1 = sheet.getRow(1);
Assertions.assertEquals(2000, row1.getHeight(), 0);
}
private List<AnnotationStyleData> dataStyle() throws Exception {
List<AnnotationStyleData> list = new ArrayList<>();
AnnotationStyleData data = new AnnotationStyleData();
data.setString("string");
data.setString1("string1");
list.add(data);
return list;
}
private List<AnnotationData> data() throws Exception {
List<AnnotationData> list = new ArrayList<>();
AnnotationData data = new AnnotationData();
data.setDate(DateUtils.parseDate("2020-01-01 01:01:01"));
data.setNumber(99.99);
data.setIgnore("忽略");
data.setTransientString("忽略");
list.add(data);
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataListener.java | package com.alibaba.easyexcel.test.core.annotation;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class AnnotationDataListener extends AnalysisEventListener<AnnotationData> {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationDataListener.class);
List<AnnotationData> list = new ArrayList<AnnotationData>();
@Override
public void invoke(AnnotationData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 1);
AnnotationData data = list.get(0);
try {
Assertions.assertEquals(data.getDate(), DateUtils.parseDate("2020-01-01 01:01:01"));
} catch (ParseException e) {
throw new ExcelCommonException("Test Exception", e);
}
Assertions.assertEquals(data.getNumber(), 99.99, 0.00);
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java | package com.alibaba.easyexcel.test.core.annotation;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@ColumnWidth(50)
@HeadRowHeight(50)
@ContentRowHeight(100)
public class AnnotationData {
@ExcelProperty("日期")
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
private Date date;
@ExcelProperty(value = "数字")
@NumberFormat("#.##%")
private Double number;
@ExcelIgnore
private String ignore;
private static final String staticFinal = "test";
private transient String transientString;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java | package com.alibaba.easyexcel.test.core.annotation;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* Annotation data test
*
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class AnnotationIndexAndNameDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("annotationIndexAndName07.xlsx");
file03 = TestFileUtil.createNewFile("annotationIndexAndName03.xls");
fileCsv = TestFileUtil.createNewFile("annotationIndexAndNameCsv.csv");
}
@Test
public void t01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteCsv() {
readAndWrite(fileCsv);
}
private void readAndWrite(File file) {
EasyExcel.write(file, AnnotationIndexAndNameData.class).sheet().doWrite(data());
EasyExcel.read(file, AnnotationIndexAndNameData.class, new AnnotationIndexAndNameDataListener()).sheet()
.doRead();
}
private List<AnnotationIndexAndNameData> data() {
List<AnnotationIndexAndNameData> list = new ArrayList<AnnotationIndexAndNameData>();
AnnotationIndexAndNameData data = new AnnotationIndexAndNameData();
data.setIndex0("第0个");
data.setIndex1("第1个");
data.setIndex2("第2个");
data.setIndex4("第4个");
list.add(data);
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationStyleData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationStyleData.java | package com.alibaba.easyexcel.test.core.annotation;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ContentFontStyle;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.annotation.write.style.HeadFontStyle;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.alibaba.excel.enums.poi.FillPatternTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 10)
@HeadFontStyle(fontHeightInPoints = 20, color = 15)
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 17)
@ContentFontStyle(fontHeightInPoints = 30, color = 22)
public class AnnotationStyleData {
@ExcelProperty("字符串")
@HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 14)
@HeadFontStyle(fontHeightInPoints = 40, color = 51)
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
@ContentFontStyle(fontHeightInPoints = 50, color = 12)
private String string;
@ExcelProperty("字符串1")
private String string1;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataListener.java | package com.alibaba.easyexcel.test.core.annotation;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class AnnotationIndexAndNameDataListener extends AnalysisEventListener<AnnotationIndexAndNameData> {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationIndexAndNameDataListener.class);
List<AnnotationIndexAndNameData> list = new ArrayList<AnnotationIndexAndNameData>();
@Override
public void invoke(AnnotationIndexAndNameData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 1);
AnnotationIndexAndNameData data = list.get(0);
Assertions.assertEquals(data.getIndex0(), "第0个");
Assertions.assertEquals(data.getIndex1(), "第1个");
Assertions.assertEquals(data.getIndex2(), "第2个");
Assertions.assertEquals(data.getIndex4(), "第4个");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameData.java | package com.alibaba.easyexcel.test.core.annotation;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class AnnotationIndexAndNameData {
@ExcelProperty(value = "第四个", index = 4)
private String index4;
@ExcelProperty(value = "第二个")
private String index2;
@ExcelProperty(index = 0)
private String index0;
@ExcelProperty(value = "第一个", index = 1)
private String index1;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java | package com.alibaba.easyexcel.test.core.repetition;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class RepetitionDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
private static File fileTable07;
private static File fileTable03;
private static File fileTableCsv;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("repetition07.xlsx");
file03 = TestFileUtil.createNewFile("repetition03.xls");
fileCsv = TestFileUtil.createNewFile("repetitionCsv.csv");
fileTable07 = TestFileUtil.createNewFile("repetitionTable07.xlsx");
fileTable03 = TestFileUtil.createNewFile("repetitionTable03.xls");
fileTableCsv = TestFileUtil.createNewFile("repetitionTableCsv.csv");
}
@Test
public void t01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteCsv() {
readAndWrite(fileCsv);
}
private void readAndWrite(File file) {
try (ExcelWriter excelWriter = EasyExcel.write(file, RepetitionData.class).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
excelWriter.write(data(), writeSheet).write(data(), writeSheet);
}
try (ExcelReader excelReader = EasyExcel.read(file, RepetitionData.class, new RepetitionDataListener())
.build()) {
ReadSheet readSheet = EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
}
}
@Test
public void t11ReadAndWriteTable07() {
readAndWriteTable(fileTable07);
}
@Test
public void t12ReadAndWriteTable03() {
readAndWriteTable(fileTable03);
}
@Test
public void t13ReadAndWriteTableCsv() {
readAndWriteTable(fileTableCsv);
}
private void readAndWriteTable(File file) {
try (ExcelWriter excelWriter = EasyExcel.write(file, RepetitionData.class).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
WriteTable writeTable = EasyExcel.writerTable(0).relativeHeadRowIndex(0).build();
excelWriter.write(data(), writeSheet, writeTable).write(data(), writeSheet, writeTable);
}
try (ExcelReader excelReader = EasyExcel.read(file, RepetitionData.class, new RepetitionDataListener())
.build()) {
ReadSheet readSheet = EasyExcel.readSheet(0).headRowNumber(2).build();
excelReader.read(readSheet);
}
}
private List<RepetitionData> data() {
List<RepetitionData> list = new ArrayList<RepetitionData>();
RepetitionData data = new RepetitionData();
data.setString("字符串0");
list.add(data);
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataListener.java | package com.alibaba.easyexcel.test.core.repetition;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class RepetitionDataListener extends AnalysisEventListener<RepetitionData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
List<RepetitionData> list = new ArrayList<RepetitionData>();
@Override
public void invoke(RepetitionData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 2);
Assertions.assertEquals(list.get(0).getString(), "字符串0");
Assertions.assertEquals(list.get(1).getString(), "字符串0");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionData.java | package com.alibaba.easyexcel.test.core.repetition;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class RepetitionData {
@ExcelProperty("字符串")
private String string;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java | package com.alibaba.easyexcel.test.core.template;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class TemplateDataTest {
private static File file07;
private static File file03;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("template07.xlsx");
file03 = TestFileUtil.createNewFile("template03.xls");
}
@Test
public void t01ReadAndWrite07() {
readAndWrite07(file07);
}
@Test
public void t02ReadAndWrite03() {
readAndWrite03(file03);
}
private void readAndWrite07(File file) {
EasyExcel.write(file, TemplateData.class)
.withTemplate(TestFileUtil.readFile("template" + File.separator + "template07.xlsx")).sheet()
.doWrite(data());
EasyExcel.read(file, TemplateData.class, new TemplateDataListener()).headRowNumber(3).sheet().doRead();
}
private void readAndWrite03(File file) {
EasyExcel.write(file, TemplateData.class)
.withTemplate(TestFileUtil.readFile("template" + File.separator + "template03.xls")).sheet()
.doWrite(data());
EasyExcel.read(file, TemplateData.class, new TemplateDataListener()).headRowNumber(3).sheet().doRead();
}
private List<TemplateData> data() {
List<TemplateData> list = new ArrayList<TemplateData>();
TemplateData data = new TemplateData();
data.setString0("字符串0");
data.setString1("字符串01");
TemplateData data1 = new TemplateData();
data1.setString0("字符串1");
data1.setString1("字符串11");
list.add(data);
list.add(data1);
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateData.java | package com.alibaba.easyexcel.test.core.template;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class TemplateData {
@ExcelProperty("字符串0")
private String string0;
@ExcelProperty("字符串1")
private String string1;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataListener.java | package com.alibaba.easyexcel.test.core.template;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class TemplateDataListener extends AnalysisEventListener<TemplateData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
List<TemplateData> list = new ArrayList<TemplateData>();
@Override
public void invoke(TemplateData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 2);
Assertions.assertEquals(list.get(0).getString0(), "字符串0");
Assertions.assertEquals(list.get(1).getString0(), "字符串1");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataListener.java | package com.alibaba.easyexcel.test.core.large;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class LargeDataListener extends AnalysisEventListener<LargeData> {
private static final Logger LOGGER = LoggerFactory.getLogger(LargeDataListener.class);
private int count = 0;
@Override
public void invoke(LargeData data, AnalysisContext context) {
if (count == 0) {
LOGGER.info("First row:{}", JSON.toJSONString(data));
}
count++;
if (count % 100000 == 0) {
LOGGER.info("Already read:{},{}", count, JSON.toJSONString(data));
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
LOGGER.info("Large row count:{}", count);
if (context.readWorkbookHolder().getExcelType() != ExcelTypeEnum.CSV) {
Assertions.assertEquals(count, 464509);
} else {
Assertions.assertEquals(count, 499999);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataTest.java | package com.alibaba.easyexcel.test.core.large;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class LargeDataTest {
private static final Logger LOGGER = LoggerFactory.getLogger(LargeDataTest.class);
private static File fileFill07;
private static File template07;
private static File fileCsv;
private static File fileWrite07;
private static File fileWriteTemp07;
private static File fileWritePoi07;
private int i = 0;
@BeforeAll
public static void init() {
fileFill07 = TestFileUtil.createNewFile("largefill07.xlsx");
fileWrite07 = TestFileUtil.createNewFile("large" + File.separator + "fileWrite07.xlsx");
fileWriteTemp07 = TestFileUtil.createNewFile("large" + File.separator + "fileWriteTemp07.xlsx");
fileWritePoi07 = TestFileUtil.createNewFile("large" + File.separator + "fileWritePoi07.xlsx");
template07 = TestFileUtil.readFile("large" + File.separator + "fill.xlsx");
fileCsv = TestFileUtil.createNewFile("largefileCsv.csv");
}
@Test
public void t01Read() throws Exception {
long start = System.currentTimeMillis();
EasyExcel.read(TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx", LargeData.class,
new LargeDataListener()).headRowNumber(2).sheet().doRead();
LOGGER.info("Large data total time spent:{}", System.currentTimeMillis() - start);
}
@Test
public void t02Fill() {
try (ExcelWriter excelWriter = EasyExcel.write(fileFill07).withTemplate(template07).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
for (int j = 0; j < 5000; j++) {
excelWriter.fill(data(), writeSheet);
LOGGER.info("{} fill success.", j);
}
}
}
@Test
public void t03ReadAndWriteCsv() {
// write
long start = System.currentTimeMillis();
try (ExcelWriter excelWriter = EasyExcel.write(fileCsv).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
for (int j = 0; j < 5000; j++) {
excelWriter.write(data(), writeSheet);
LOGGER.info("{} write success.", j);
}
}
LOGGER.info("CSV large data total time spent:{}", System.currentTimeMillis() - start);
// read
start = System.currentTimeMillis();
EasyExcel.read(fileCsv, LargeData.class, new LargeDataListener()).sheet().doRead();
LOGGER.info("CSV large data total time spent:{}", System.currentTimeMillis() - start);
}
@Test
public void t04Write() throws Exception {
ExcelWriter excelWriter = EasyExcel.write(fileWriteTemp07, LargeData.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
for (int j = 0; j < 2; j++) {
excelWriter.write(data(), writeSheet);
}
excelWriter.finish();
long start = System.currentTimeMillis();
excelWriter = EasyExcel.write(fileWrite07, LargeData.class).build();
writeSheet = EasyExcel.writerSheet().build();
for (int j = 0; j < 5000; j++) {
excelWriter.write(data(), writeSheet);
LOGGER.info("{} write success.", j);
}
excelWriter.finish();
long cost = System.currentTimeMillis() - start;
LOGGER.info("write cost:{}", cost);
start = System.currentTimeMillis();
try (FileOutputStream fileOutputStream = new FileOutputStream(fileWritePoi07)) {
SXSSFWorkbook workbook = new SXSSFWorkbook();
SXSSFSheet sheet = workbook.createSheet("sheet1");
for (int i = 0; i < 100 * 5000; i++) {
SXSSFRow row = sheet.createRow(i);
for (int j = 0; j < 25; j++) {
SXSSFCell cell = row.createCell(j);
cell.setCellValue("str-" + j + "-" + i);
}
if (i % 5000 == 0) {
LOGGER.info("{} write success.", i);
}
}
workbook.write(fileOutputStream);
workbook.dispose();
workbook.close();
}
long costPoi = System.currentTimeMillis() - start;
LOGGER.info("poi write cost:{}", System.currentTimeMillis() - start);
LOGGER.info("{} vs {}", cost, costPoi);
Assertions.assertTrue(costPoi * 2 > cost);
}
private List<LargeData> data() {
List<LargeData> list = new ArrayList<>();
int size = i + 100;
for (; i < size; i++) {
LargeData largeData = new LargeData();
list.add(largeData);
largeData.setStr1("str1-" + i);
largeData.setStr2("str2-" + i);
largeData.setStr3("str3-" + i);
largeData.setStr4("str4-" + i);
largeData.setStr5("str5-" + i);
largeData.setStr6("str6-" + i);
largeData.setStr7("str7-" + i);
largeData.setStr8("str8-" + i);
largeData.setStr9("str9-" + i);
largeData.setStr10("str10-" + i);
largeData.setStr11("str11-" + i);
largeData.setStr12("str12-" + i);
largeData.setStr13("str13-" + i);
largeData.setStr14("str14-" + i);
largeData.setStr15("str15-" + i);
largeData.setStr16("str16-" + i);
largeData.setStr17("str17-" + i);
largeData.setStr18("str18-" + i);
largeData.setStr19("str19-" + i);
largeData.setStr20("str20-" + i);
largeData.setStr21("str21-" + i);
largeData.setStr22("str22-" + i);
largeData.setStr23("str23-" + i);
largeData.setStr24("str24-" + i);
largeData.setStr25("str25-" + i);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/large/LargeData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/large/LargeData.java | package com.alibaba.easyexcel.test.core.large;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class LargeData {
private String str1;
private String str2;
private String str3;
private String str4;
private String str5;
private String str6;
private String str7;
private String str8;
private String str9;
private String str10;
private String str11;
private String str12;
private String str13;
private String str14;
private String str15;
private String str16;
private String str17;
private String str18;
private String str19;
private String str20;
private String str21;
private String str22;
private String str23;
private String str24;
private String str25;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityTest.java | package com.alibaba.easyexcel.test.core.compatibility;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.easyexcel.test.core.simple.SimpleData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.cache.Ehcache;
import com.alibaba.excel.enums.ReadDefaultReturnEnum;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* Compatible with some special files
*
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
@Slf4j
public class CompatibilityTest {
@Test
public void t01() {
// https://github.com/alibaba/easyexcel/issues/2236
List<Map<Integer, Object>> list = EasyExcel.read(TestFileUtil.getPath() + "compatibility/t01.xls").sheet()
.doReadSync();
Assertions.assertEquals(2, list.size());
Map<Integer, Object> row1 = list.get(1);
Assertions.assertEquals("Q235(碳钢)", row1.get(0));
}
@Test
public void t02() {
// Exist in `sharedStrings.xml` `x:t` start tag, need to be compatible
List<Map<Integer, Object>> list = EasyExcel.read(TestFileUtil.getPath() + "compatibility/t02.xlsx").sheet()
.headRowNumber(0).doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals(3, list.size());
Map<Integer, Object> row2 = list.get(2);
Assertions.assertEquals("1,2-戊二醇", row2.get(2));
}
@Test
public void t03() {
// In the presence of the first line of a lot of null columns, ignore null columns
List<Map<Integer, Object>> list = EasyExcel.read(TestFileUtil.getPath() + "compatibility/t03.xlsx").sheet()
.doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals(1, list.size());
Map<Integer, Object> row0 = list.get(0);
Assertions.assertEquals(12, row0.size());
}
@Test
public void t04() {
// Exist in `sheet1.xml` `ns2:t` start tag, need to be compatible
List<Map<Integer, Object>> list = EasyExcel.read(TestFileUtil.getPath() + "compatibility/t04.xlsx").sheet()
.doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals(56, list.size());
Map<Integer, Object> row0 = list.get(0);
Assertions.assertEquals("QQSJK28F152A012242S0081", row0.get(5));
}
@Test
public void t05() {
// https://github.com/alibaba/easyexcel/issues/1956
// Excel read date needs to be rounded
List<Map<Integer, String>> list = EasyExcel
.read(TestFileUtil.getPath() + "compatibility/t05.xlsx")
.sheet()
.doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals("2023-01-01 00:00:00", list.get(0).get(0));
Assertions.assertEquals("2023-01-01 00:00:00", list.get(1).get(0));
Assertions.assertEquals("2023-01-01 00:00:00", list.get(2).get(0));
Assertions.assertEquals("2023-01-01 00:00:01", list.get(3).get(0));
Assertions.assertEquals("2023-01-01 00:00:01", list.get(4).get(0));
}
@Test
public void t06() {
// Keep error precision digital format
List<Map<Integer, String>> list = EasyExcel
.read(TestFileUtil.getPath() + "compatibility/t06.xlsx")
.headRowNumber(0)
.sheet()
.doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals("2087.03", list.get(0).get(2));
}
@Test
public void t07() {
// https://github.com/alibaba/easyexcel/issues/2805
// Excel read date needs to be rounded
List<Map<Integer, Object>> list = EasyExcel
.read(TestFileUtil.getPath() + "compatibility/t07.xlsx")
.readDefaultReturn(ReadDefaultReturnEnum.ACTUAL_DATA)
.sheet()
.doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals(0, new BigDecimal("24.1998124").compareTo((BigDecimal)list.get(0).get(11)));
list = EasyExcel
.read(TestFileUtil.getPath() + "compatibility/t07.xlsx")
.sheet()
.doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals("24.20", list.get(0).get(11));
}
@Test
public void t08() {
// https://github.com/alibaba/easyexcel/issues/2693
// Temporary files may be deleted if there is no operation for a long time, so they need to be recreated.
File file = TestFileUtil.createNewFile("compatibility/t08.xlsx");
EasyExcel.write(file, SimpleData.class)
.sheet()
.doWrite(data());
List<Map<Integer, Object>> list = EasyExcel.read(file)
.readCache(new Ehcache(null, 20))
.sheet()
.doReadSync();
Assertions.assertEquals(10L, list.size());
FileUtils.delete(new File(System.getProperty(TempFile.JAVA_IO_TMPDIR)));
list = EasyExcel.read(file)
.readCache(new Ehcache(null, 20))
.sheet()
.doReadSync();
Assertions.assertEquals(10L, list.size());
}
@Test
public void t09() {
// `SH_x005f_x000D_Z002` exists in `ShardingString.xml` and needs to be replaced by: `SH_x000D_Z002`
File file = TestFileUtil.readFile("compatibility/t09.xlsx");
List<Map<Integer, Object>> list = EasyExcel.read(file)
.headRowNumber(0)
.sheet()
.doReadSync();
log.info("data:{}", JSON.toJSONString(list));
Assertions.assertEquals(1, list.size());
Assertions.assertEquals("SH_x000D_Z002", list.get(0).get(0));
}
private List<SimpleData> data() {
List<SimpleData> list = new ArrayList<SimpleData>();
for (int i = 0; i < 10; i++) {
SimpleData simpleData = new SimpleData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptData.java | package com.alibaba.easyexcel.test.core.encrypt;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class EncryptData {
@ExcelProperty("姓名")
private String name;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java | package com.alibaba.easyexcel.test.core.encrypt;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.core.simple.SimpleData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class EncryptDataTest {
private static File file07;
private static File file03;
private static File file07OutputStream;
private static File file03OutputStream;
@Test
public void testformat() {
DecimalFormat decimalFormat = new DecimalFormat("0.00");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
BigDecimal bigDecimal = new BigDecimal("0.105");
System.out.println(decimalFormat.format(bigDecimal));
}
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("encrypt07.xlsx");
file03 = TestFileUtil.createNewFile("encrypt03.xls");
file07OutputStream = TestFileUtil.createNewFile("encryptOutputStream07.xlsx");
file03OutputStream = TestFileUtil.createNewFile("encryptOutputStream03.xls");
}
@Test
public void t01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteStream07() throws Exception {
readAndWriteStream(file07OutputStream, ExcelTypeEnum.XLSX);
}
@Test
public void t04ReadAndWriteStream03() throws Exception {
readAndWriteStream(file03OutputStream, ExcelTypeEnum.XLS);
}
private void readAndWrite(File file) {
EasyExcel.write(file, EncryptData.class).password("123456").sheet().doWrite(data());
EasyExcel.read(file, EncryptData.class, new EncryptDataListener()).password("123456").sheet().doRead();
}
private void readAndWriteStream(File file, ExcelTypeEnum excelType) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream(file);
EasyExcel.write(fileOutputStream, EncryptData.class).password("123456").excelType(excelType).sheet()
.doWrite(data());
fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(file);
EasyExcel.read(fileInputStream, EncryptData.class, new EncryptDataListener()).password("123456").sheet()
.doRead();
}
private List<SimpleData> data() {
List<SimpleData> list = new ArrayList<SimpleData>();
for (int i = 0; i < 10; i++) {
SimpleData simpleData = new SimpleData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataListener.java | package com.alibaba.easyexcel.test.core.encrypt;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class EncryptDataListener extends AnalysisEventListener<EncryptData> {
private static final Logger LOGGER = LoggerFactory.getLogger(EncryptDataListener.class);
List<EncryptData> list = new ArrayList<EncryptData>();
@Override
public void invoke(EncryptData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 10);
Assertions.assertEquals(list.get(0).getName(), "姓名0");
Assertions.assertEquals((int)(context.readSheetHolder().getSheetNo()), 0);
Assertions.assertEquals(
context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().get(0).getHeadNameList().get(0), "姓名");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java | package com.alibaba.easyexcel.test.core.simple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
@Slf4j
public class SimpleDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("simple07.xlsx");
file03 = TestFileUtil.createNewFile("simple03.xls");
fileCsv = TestFileUtil.createNewFile("simpleCsv.csv");
}
@Test
public void t01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteCsv() {
readAndWrite(fileCsv);
}
private void readAndWrite(File file) {
EasyExcel.write(file, SimpleData.class).sheet().doWrite(data());
EasyExcel.read(file, SimpleData.class, new SimpleDataListener()).sheet().doRead();
}
@Test
public void t04ReadAndWrite07() throws Exception {
readAndWriteInputStream(file07, ExcelTypeEnum.XLSX);
}
@Test
public void t05ReadAndWrite03() throws Exception {
readAndWriteInputStream(file03, ExcelTypeEnum.XLS);
}
@Test
public void t06ReadAndWriteCsv() throws Exception {
readAndWriteInputStream(fileCsv, ExcelTypeEnum.CSV);
}
private void readAndWriteInputStream(File file, ExcelTypeEnum excelTypeEnum) throws Exception {
EasyExcel.write(new FileOutputStream(file), SimpleData.class).excelType(excelTypeEnum).sheet().doWrite(data());
EasyExcel.read(new FileInputStream(file), SimpleData.class, new SimpleDataListener()).sheet().doRead();
}
@Test
public void t11SynchronousRead07() {
synchronousRead(file07);
}
@Test
public void t12SynchronousRead03() {
synchronousRead(file03);
}
@Test
public void t13SynchronousReadCsv() {
synchronousRead(fileCsv);
}
@Test
public void t21SheetNameRead07() {
List<Map<Integer, Object>> list = EasyExcel.read(
TestFileUtil.readFile("simple" + File.separator + "simple07.xlsx"))
.sheet("simple")
.doReadSync();
Assertions.assertEquals(1, list.size());
}
@Test
public void t22PageReadListener07() {
EasyExcel.read(file07, SimpleData.class,
new PageReadListener<SimpleData>(dataList -> {
Assertions.assertEquals(5, dataList.size());
}, 5))
.sheet().doRead();
}
private void synchronousRead(File file) {
// Synchronous read file
List<Object> list = EasyExcel.read(file).head(SimpleData.class).sheet().doReadSync();
Assertions.assertEquals(list.size(), 10);
Assertions.assertTrue(list.get(0) instanceof SimpleData);
Assertions.assertEquals(((SimpleData)list.get(0)).getName(), "姓名0");
}
private List<SimpleData> data() {
List<SimpleData> list = new ArrayList<SimpleData>();
for (int i = 0; i < 10; i++) {
SimpleData simpleData = new SimpleData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleData.java | package com.alibaba.easyexcel.test.core.simple;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class SimpleData {
@ExcelProperty("姓名")
private String name;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataSheetNameListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataSheetNameListener.java | package com.alibaba.easyexcel.test.core.simple;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class SimpleDataSheetNameListener extends AnalysisEventListener<SimpleData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataSheetNameListener.class);
List<SimpleData> list = new ArrayList<SimpleData>();
@Override
public void invoke(SimpleData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 1);
Assertions.assertEquals(list.get(0).getName(), "张三");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataListener.java | package com.alibaba.easyexcel.test.core.simple;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class SimpleDataListener extends AnalysisEventListener<SimpleData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
List<SimpleData> list = new ArrayList<SimpleData>();
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
LOGGER.debug("Head is:{}", JSON.toJSONString(headMap));
Assertions.assertEquals(headMap.get(0), "姓名");
}
@Override
public void invoke(SimpleData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 10);
Assertions.assertEquals(list.get(0).getName(), "姓名0");
Assertions.assertEquals((int)(context.readSheetHolder().getSheetNo()), 0);
Assertions.assertEquals(
context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().get(0).getHeadNameList().get(0), "姓名");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataListener.java | package com.alibaba.easyexcel.test.core.noncamel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
/**
* @author Jiaju Zhuang
*/
@Slf4j
public class UnCamelDataListener extends AnalysisEventListener<UnCamelData> {
List<UnCamelData> list = new ArrayList<>();
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
log.debug("Head is:{}", JSON.toJSONString(headMap));
Assertions.assertEquals(headMap.get(0), "string1");
Assertions.assertEquals(headMap.get(1), "string2");
Assertions.assertEquals(headMap.get(2), "STring3");
Assertions.assertEquals(headMap.get(3), "STring4");
Assertions.assertEquals(headMap.get(4), "STRING5");
Assertions.assertEquals(headMap.get(5), "STRing6");
}
@Override
public void invoke(UnCamelData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 10);
UnCamelData unCamelData = list.get(0);
Assertions.assertEquals(unCamelData.getString1(), "string1");
Assertions.assertEquals(unCamelData.getString2(), "string2");
Assertions.assertEquals(unCamelData.getSTring3(), "string3");
Assertions.assertEquals(unCamelData.getSTring4(), "string4");
Assertions.assertEquals(unCamelData.getSTRING5(), "string5");
Assertions.assertEquals(unCamelData.getSTRing6(), "string6");
log.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelData.java | package com.alibaba.easyexcel.test.core.noncamel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class UnCamelData {
private String string1;
private String String2;
private String sTring3;
private String STring4;
private String STRING5;
private String STRing6;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java | package com.alibaba.easyexcel.test.core.noncamel;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class UnCamelDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("unCame07.xlsx");
file03 = TestFileUtil.createNewFile("unCame03.xls");
fileCsv = TestFileUtil.createNewFile("unCameCsv.csv");
}
@Test
public void t01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteCsv() {
readAndWrite(fileCsv);
}
private void readAndWrite(File file) {
EasyExcel.write(file, UnCamelData.class).sheet().doWrite(data());
EasyExcel.read(file, UnCamelData.class, new UnCamelDataListener()).sheet().doRead();
}
private List<UnCamelData> data() {
List<UnCamelData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
UnCamelData unCamelData = new UnCamelData();
unCamelData.setString1("string1");
unCamelData.setString2("string2");
unCamelData.setSTring3("string3");
unCamelData.setSTring4("string4");
unCamelData.setSTRING5("string5");
unCamelData.setSTRing6("string6");
list.add(unCamelData);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerData.java | package com.alibaba.easyexcel.test.core.handler;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class WriteHandlerData {
@ExcelProperty("姓名")
private String name;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java | package com.alibaba.easyexcel.test.core.handler;
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.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
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 org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.junit.jupiter.api.Assertions;
/**
* @author JiaJu Zhuang
**/
public class WriteHandler implements WorkbookWriteHandler, SheetWriteHandler, RowWriteHandler, CellWriteHandler {
private long beforeCellCreate = 0L;
private long afterCellCreate = 0L;
private long afterCellDataConverted = 0L;
private long afterCellDispose = 0L;
private long beforeRowCreate = 0L;
private long afterRowCreate = 0L;
private long afterRowDispose = 0L;
private long beforeSheetCreate = 0L;
private long afterSheetCreate = 0L;
private long beforeWorkbookCreate = 0L;
private long afterWorkbookCreate = 0L;
private long afterWorkbookDispose = 0L;
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
Assertions.assertEquals(0L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(1L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
beforeCellCreate++;
}
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
Assertions.assertEquals(1L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(1L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterCellCreate++;
}
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
Assertions.assertEquals(1L, beforeCellCreate);
Assertions.assertEquals(1L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(1, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(1L, afterRowCreate);
Assertions.assertEquals(1L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterCellDataConverted++;
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
Assertions.assertEquals(1L, beforeCellCreate);
Assertions.assertEquals(1L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(1L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterCellDispose++;
}
}
@Override
public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
Assertions.assertEquals(0L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(0L, beforeRowCreate);
Assertions.assertEquals(0L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
beforeRowCreate++;
}
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
Assertions.assertEquals(0L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(0L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterRowCreate++;
}
}
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
Assertions.assertEquals(1L, beforeCellCreate);
Assertions.assertEquals(1L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(1L, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(1L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterRowDispose++;
}
}
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
Assertions.assertEquals(0L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(0L, beforeRowCreate);
Assertions.assertEquals(0L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(0L, beforeSheetCreate);
Assertions.assertEquals(0L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
beforeSheetCreate++;
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
Assertions.assertEquals(0L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(0L, beforeRowCreate);
Assertions.assertEquals(0L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(0L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterSheetCreate++;
}
@Override
public void beforeWorkbookCreate() {
Assertions.assertEquals(0L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(0L, beforeRowCreate);
Assertions.assertEquals(0L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(0L, beforeSheetCreate);
Assertions.assertEquals(0L, afterSheetCreate);
Assertions.assertEquals(0L, beforeWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
beforeWorkbookCreate++;
}
@Override
public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
Assertions.assertEquals(0L, beforeCellCreate);
Assertions.assertEquals(0L, afterCellCreate);
Assertions.assertEquals(0L, afterCellDataConverted);
Assertions.assertEquals(0L, afterCellDispose);
Assertions.assertEquals(0L, beforeRowCreate);
Assertions.assertEquals(0L, afterRowCreate);
Assertions.assertEquals(0L, afterRowDispose);
Assertions.assertEquals(0L, beforeSheetCreate);
Assertions.assertEquals(0L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterWorkbookCreate++;
}
@Override
public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {
Assertions.assertEquals(1L, beforeCellCreate);
Assertions.assertEquals(1L, afterCellCreate);
Assertions.assertEquals(1L, afterCellDataConverted);
Assertions.assertEquals(1L, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(1L, afterRowCreate);
Assertions.assertEquals(1L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(0L, afterWorkbookDispose);
afterWorkbookDispose++;
}
public void afterAll() {
Assertions.assertEquals(1L, beforeCellCreate);
Assertions.assertEquals(1L, afterCellCreate);
Assertions.assertEquals(1L, afterCellDataConverted);
Assertions.assertEquals(1L, afterCellDispose);
Assertions.assertEquals(1L, beforeRowCreate);
Assertions.assertEquals(1L, afterRowCreate);
Assertions.assertEquals(1L, afterRowDispose);
Assertions.assertEquals(1L, beforeSheetCreate);
Assertions.assertEquals(1L, afterSheetCreate);
Assertions.assertEquals(1L, beforeWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookCreate);
Assertions.assertEquals(1L, afterWorkbookDispose);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerTest.java | package com.alibaba.easyexcel.test.core.handler;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class WriteHandlerTest {
private static File file07;
private static File file03;
private static File fileCsv;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("writeHandler07.xlsx");
file03 = TestFileUtil.createNewFile("writeHandler03.xls");
fileCsv = TestFileUtil.createNewFile("writeHandlerCsv.csv");
}
@Test
public void t01WorkbookWrite07() throws Exception {
workbookWrite(file07);
}
@Test
public void t02WorkbookWrite03() throws Exception {
workbookWrite(file03);
}
@Test
public void t03WorkbookWriteCsv() throws Exception {
workbookWrite(fileCsv);
}
@Test
public void t11SheetWrite07() throws Exception {
sheetWrite(file07);
}
@Test
public void t12SheetWrite03() throws Exception {
sheetWrite(file03);
}
@Test
public void t13SheetWriteCsv() throws Exception {
sheetWrite(fileCsv);
}
@Test
public void t21TableWrite07() throws Exception {
tableWrite(file07);
}
@Test
public void t22TableWrite03() throws Exception {
tableWrite(file03);
}
@Test
public void t23TableWriteCsv() throws Exception {
tableWrite(fileCsv);
}
private void workbookWrite(File file) {
WriteHandler writeHandler = new WriteHandler();
EasyExcel.write(file).head(WriteHandlerData.class).registerWriteHandler(writeHandler).sheet().doWrite(data());
writeHandler.afterAll();
}
private void sheetWrite(File file) {
WriteHandler writeHandler = new WriteHandler();
EasyExcel.write(file).head(WriteHandlerData.class).sheet().registerWriteHandler(writeHandler).doWrite(data());
writeHandler.afterAll();
}
private void tableWrite(File file) {
WriteHandler writeHandler = new WriteHandler();
EasyExcel.write(file).head(WriteHandlerData.class).sheet().table(0).registerWriteHandler(writeHandler)
.doWrite(data());
writeHandler.afterAll();
}
private List<WriteHandlerData> data() {
List<WriteHandlerData> list = new ArrayList<WriteHandlerData>();
for (int i = 0; i < 1; i++) {
WriteHandlerData data = new WriteHandlerData();
data.setName("姓名" + i);
list.add(data);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataReadData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataReadData.java | package com.alibaba.easyexcel.test.core.celldata;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.metadata.data.ReadCellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CellDataReadData {
@DateTimeFormat("yyyy年MM月dd日")
private ReadCellData<String> date;
private ReadCellData<Integer> integer1;
private Integer integer2;
private ReadCellData<?> formulaValue;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java | package com.alibaba.easyexcel.test.core.celldata;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson2.JSON;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
public class CellDataDataListener extends AnalysisEventListener<CellDataReadData> {
private static final Logger LOGGER = LoggerFactory.getLogger(CellDataDataListener.class);
List<CellDataReadData> list = new ArrayList<>();
@Override
public void invoke(CellDataReadData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assertions.assertEquals(list.size(), 1);
CellDataReadData cellDataData = list.get(0);
Assertions.assertEquals("2020年01月01日", cellDataData.getDate().getData());
Assertions.assertEquals((long)cellDataData.getInteger1().getData(), 2L);
Assertions.assertEquals((long)cellDataData.getInteger2(), 2L);
if (context.readWorkbookHolder().getExcelType() != ExcelTypeEnum.CSV) {
Assertions.assertEquals(cellDataData.getFormulaValue().getFormulaData().getFormulaValue(), "B2+C2");
} else {
Assertions.assertNull(cellDataData.getFormulaValue().getData());
}
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataWriteData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataWriteData.java | package com.alibaba.easyexcel.test.core.celldata;
import java.util.Date;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.metadata.data.WriteCellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CellDataWriteData {
@DateTimeFormat("yyyy年MM月dd日")
private WriteCellData<Date> date;
private WriteCellData<Integer> integer1;
private Integer integer2;
private WriteCellData<?> formulaValue;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java | package com.alibaba.easyexcel.test.core.celldata;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.FormulaData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.DateUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
public class CellDataDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("cellData07.xlsx");
file03 = TestFileUtil.createNewFile("cellData03.xls");
fileCsv = TestFileUtil.createNewFile("cellDataCsv.csv");
}
@Test
public void t01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
@Test
public void t03ReadAndWriteCsv() throws Exception {
readAndWrite(fileCsv);
}
private void readAndWrite(File file) throws Exception {
EasyExcel.write(file, CellDataWriteData.class).sheet().doWrite(data());
EasyExcel.read(file, CellDataReadData.class, new CellDataDataListener()).sheet().doRead();
}
private List<CellDataWriteData> data() throws Exception {
List<CellDataWriteData> list = new ArrayList<>();
CellDataWriteData cellDataData = new CellDataWriteData();
cellDataData.setDate(new WriteCellData<>(DateUtils.parseDate("2020-01-01 01:01:01")));
WriteCellData<Integer> integer1 = new WriteCellData<>();
integer1.setType(CellDataTypeEnum.NUMBER);
integer1.setNumberValue(BigDecimal.valueOf(2L));
cellDataData.setInteger1(integer1);
cellDataData.setInteger2(2);
WriteCellData<?> formulaValue = new WriteCellData<>();
FormulaData formulaData = new FormulaData();
formulaValue.setFormulaData(formulaData);
formulaData.setFormulaValue("B2+C2");
cellDataData.setFormulaValue(formulaValue);
list.add(cellDataData);
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java | package com.alibaba.easyexcel.test.core.nomodel;
import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.ReadDefaultReturnEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
/**
* @author Jiaju Zhuang
*/
@TestMethodOrder(MethodOrderer.MethodName.class)
@Slf4j
public class NoModelDataTest {
private static File file07;
private static File file03;
private static File fileCsv;
private static File fileRepeat07;
private static File fileRepeat03;
private static File fileRepeatCsv;
@BeforeAll
public static void init() {
file07 = TestFileUtil.createNewFile("noModel07.xlsx");
file03 = TestFileUtil.createNewFile("noModel03.xls");
fileCsv = TestFileUtil.createNewFile("noModelCsv.csv");
fileRepeat07 = TestFileUtil.createNewFile("noModelRepeat07.xlsx");
fileRepeat03 = TestFileUtil.createNewFile("noModelRepeat03.xls");
fileRepeatCsv = TestFileUtil.createNewFile("noModelRepeatCsv.csv");
}
@Test
public void t01ReadAndWrite07() throws Exception {
readAndWrite(file07, fileRepeat07, false);
}
@Test
public void t02ReadAndWrite03() throws Exception {
readAndWrite(file03, fileRepeat03, false);
}
@Test
public void t03ReadAndWriteCsv() throws Exception {
readAndWrite(fileCsv, fileRepeatCsv, true);
}
private void readAndWrite(File file, File fileRepeat, boolean isCsv) throws Exception {
EasyExcel.write(file).sheet().doWrite(data());
List<Map<Integer, String>> result = EasyExcel.read(file).headRowNumber(0).sheet().doReadSync();
Assertions.assertEquals(10, result.size());
Map<Integer, String> data10 = result.get(9);
Assertions.assertEquals("string19", data10.get(0));
Assertions.assertEquals("109", data10.get(1));
Assertions.assertEquals("2020-01-01 01:01:01", data10.get(2));
List<Map<Integer, Object>> actualDataList = EasyExcel.read(file)
.headRowNumber(0)
.readDefaultReturn(ReadDefaultReturnEnum.ACTUAL_DATA)
.sheet()
.doReadSync();
log.info("actualDataList:{}", JSON.toJSONString(actualDataList));
Assertions.assertEquals(10, actualDataList.size());
Map<Integer, Object> actualData10 = actualDataList.get(9);
Assertions.assertEquals("string19", actualData10.get(0));
if (isCsv) {
// CSV only string type
Assertions.assertEquals("109", actualData10.get(1));
Assertions.assertEquals("2020-01-01 01:01:01", actualData10.get(2));
} else {
Assertions.assertEquals(0, new BigDecimal("109").compareTo((BigDecimal)actualData10.get(1)));
Assertions.assertEquals(LocalDateTime.of(2020, 1, 1, 1, 1, 1), actualData10.get(2));
}
List<Map<Integer, ReadCellData<?>>> readCellDataList = EasyExcel.read(file)
.headRowNumber(0)
.readDefaultReturn(ReadDefaultReturnEnum.READ_CELL_DATA)
.sheet()
.doReadSync();
log.info("readCellDataList:{}", JSON.toJSONString(readCellDataList));
Assertions.assertEquals(10, readCellDataList.size());
Map<Integer, ReadCellData<?>> readCellData10 = readCellDataList.get(9);
Assertions.assertEquals("string19", readCellData10.get(0).getData());
if (isCsv) {
// CSV only string type
Assertions.assertEquals("109", readCellData10.get(1).getData());
Assertions.assertEquals("2020-01-01 01:01:01", readCellData10.get(2).getData());
} else {
Assertions.assertEquals(0, new BigDecimal("109").compareTo((BigDecimal)readCellData10.get(1).getData()));
Assertions.assertEquals(LocalDateTime.of(2020, 1, 1, 1, 1, 1), readCellData10.get(2).getData());
}
EasyExcel.write(fileRepeat).sheet().doWrite(result);
result = EasyExcel.read(fileRepeat).headRowNumber(0).sheet().doReadSync();
Assertions.assertEquals(10, result.size());
data10 = result.get(9);
Assertions.assertEquals("string19", data10.get(0));
Assertions.assertEquals("109", data10.get(1));
Assertions.assertEquals("2020-01-01 01:01:01", data10.get(2));
}
private List<List<Object>> data() throws Exception {
List<List<Object>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
List<Object> data = new ArrayList<>();
data.add("string1" + i);
data.add(100 + i);
data.add(DateUtils.parseDate("2020-01-01 01:01:01"));
list.add(data);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ComplexHeadData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ComplexHeadData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 复杂头数据.这里最终效果是第一行就一个主标题,第二行分类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class ComplexHeadData {
@ExcelProperty({"主标题", "字符串标题"})
private String string;
@ExcelProperty({"主标题", "日期标题"})
private Date date;
@ExcelProperty({"主标题", "数字标题"})
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/IndexData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/IndexData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class IndexData {
@ExcelProperty(value = "字符串标题", index = 0)
private String string;
@ExcelProperty(value = "日期标题", index = 1)
private Date date;
/**
* 这里设置3 会导致第二列空的
*/
@ExcelProperty(value = "数字标题", index = 3)
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/WidthAndHeightData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/WidthAndHeightData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
@ContentRowHeight(10)
@HeadRowHeight(20)
@ColumnWidth(25)
public class WidthAndHeightData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
/**
* 宽度为50
*/
@ColumnWidth(50)
@ExcelProperty("数字标题")
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java | package com.alibaba.easyexcel.test.demo.write;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.alibaba.easyexcel.test.core.head.ComplexHeadData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.alibaba.excel.enums.CellDataTypeEnum;
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.HyperlinkData.HyperlinkType;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.ImageData.ImageType;
import com.alibaba.excel.metadata.data.RichTextStringData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.junit.jupiter.api.Test;
/**
* 写的常见写法
*
* @author Jiaju Zhuang
*/
public class WriteTest {
/**
* 最简单的写
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 直接写即可
*/
@Test
public void simpleWrite() {
// 注意 simpleWrite在数据量不大的情况下可以使用(5000以内,具体也要看实际情况),数据量大参照 重复多次写入
// 写法1 JDK8+
// since: 3.0.0-beta1
String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 如果这里想使用03 则 传入excelType参数即可
EasyExcel.write(fileName, DemoData.class)
.sheet("模板")
.doWrite(() -> {
// 分页查询数据
return data();
});
// 写法2
fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 如果这里想使用03 则 传入excelType参数即可
EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
// 写法3
fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写
try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
excelWriter.write(data(), writeSheet);
}
}
/**
* 根据参数只导出指定列
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 根据自己或者排除自己需要的列
* <p>
* 3. 直接写即可
*
* @since 2.1.1
*/
@Test
public void excludeOrIncludeWrite() {
String fileName = TestFileUtil.getPath() + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx";
// 这里需要注意 在使用ExcelProperty注解的使用,如果想不空列则需要加入order字段,而不是index,order会忽略空列,然后继续往后,而index,不会忽略空列,在第几列就是第几列。
// 根据用户传入字段 假设我们要忽略 date
Set<String> excludeColumnFieldNames = new HashSet<>();
excludeColumnFieldNames.add("date");
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoData.class).excludeColumnFieldNames(excludeColumnFieldNames).sheet("模板")
.doWrite(data());
fileName = TestFileUtil.getPath() + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx";
// 根据用户传入字段 假设我们只要导出 date
Set<String> includeColumnFieldNames = new HashSet<>();
includeColumnFieldNames.add("date");
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoData.class).includeColumnFieldNames(includeColumnFieldNames).sheet("模板")
.doWrite(data());
}
/**
* 指定写入的列
* <p>
* 1. 创建excel对应的实体对象 参照{@link IndexData}
* <p>
* 2. 使用{@link ExcelProperty}注解指定写入的列
* <p>
* 3. 直接写即可
*/
@Test
public void indexWrite() {
String fileName = TestFileUtil.getPath() + "indexWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, IndexData.class).sheet("模板").doWrite(data());
}
/**
* 复杂头写入
* <p>
* 1. 创建excel对应的实体对象 参照{@link ComplexHeadData}
* <p>
* 2. 使用{@link ExcelProperty}注解指定复杂的头
* <p>
* 3. 直接写即可
*/
@Test
public void complexHeadWrite() {
String fileName = TestFileUtil.getPath() + "complexHeadWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, ComplexHeadData.class).sheet("模板").doWrite(data());
}
/**
* 重复多次写入
* <p>
* 1. 创建excel对应的实体对象 参照{@link ComplexHeadData}
* <p>
* 2. 使用{@link ExcelProperty}注解指定复杂的头
* <p>
* 3. 直接调用二次写入即可
*/
@Test
public void repeatedWrite() {
// 方法1: 如果写到同一个sheet
String fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写
try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
// 这里注意 如果同一个sheet只要创建一次
WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
// 去调用写入,这里我调用了五次,实际使用时根据数据库分页的总的页数来
for (int i = 0; i < 5; i++) {
// 分页去数据库查询数据 这里可以去数据库查询每一页的数据
List<DemoData> data = data();
excelWriter.write(data, writeSheet);
}
}
// 方法2: 如果写到不同的sheet 同一个对象
fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 指定文件
try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
// 去调用写入,这里我调用了五次,实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面
for (int i = 0; i < 5; i++) {
// 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
WriteSheet writeSheet = EasyExcel.writerSheet(i, "模板" + i).build();
// 分页去数据库查询数据 这里可以去数据库查询每一页的数据
List<DemoData> data = data();
excelWriter.write(data, writeSheet);
}
}
// 方法3 如果写到不同的sheet 不同的对象
fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 指定文件
try (ExcelWriter excelWriter = EasyExcel.write(fileName).build()) {
// 去调用写入,这里我调用了五次,实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面
for (int i = 0; i < 5; i++) {
// 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。这里注意DemoData.class 可以每次都变,我这里为了方便 所以用的同一个class
// 实际上可以一直变
WriteSheet writeSheet = EasyExcel.writerSheet(i, "模板" + i).head(DemoData.class).build();
// 分页去数据库查询数据 这里可以去数据库查询每一页的数据
List<DemoData> data = data();
excelWriter.write(data, writeSheet);
}
}
}
/**
* 日期、数字或者自定义格式转换
* <p>
* 1. 创建excel对应的实体对象 参照{@link ConverterData}
* <p>
* 2. 使用{@link ExcelProperty}配合使用注解{@link DateTimeFormat}、{@link NumberFormat}或者自定义注解
* <p>
* 3. 直接写即可
*/
@Test
public void converterWrite() {
String fileName = TestFileUtil.getPath() + "converterWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, ConverterData.class).sheet("模板").doWrite(data());
}
/**
* 图片导出
* <p>
* 1. 创建excel对应的实体对象 参照{@link ImageDemoData}
* <p>
* 2. 直接写即可
*/
@Test
public void imageWrite() throws Exception {
String fileName = TestFileUtil.getPath() + "imageWrite" + System.currentTimeMillis() + ".xlsx";
// 这里注意下 所有的图片都会放到内存 暂时没有很好的解法,大量图片的情况下建议 2选1:
// 1. 将图片上传到oss 或者其他存储网站: https://www.aliyun.com/product/oss ,然后直接放链接
// 2. 使用: https://github.com/coobird/thumbnailator 或者其他工具压缩图片
String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg";
try (InputStream inputStream = FileUtils.openInputStream(new File(imagePath))) {
List<ImageDemoData> list = ListUtils.newArrayList();
ImageDemoData imageDemoData = new ImageDemoData();
list.add(imageDemoData);
// 放入五种类型的图片 实际使用只要选一种即可
imageDemoData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath)));
imageDemoData.setFile(new File(imagePath));
imageDemoData.setString(imagePath);
imageDemoData.setInputStream(inputStream);
imageDemoData.setUrl(new URL(
"https://raw.githubusercontent.com/alibaba/easyexcel/master/src/test/resources/converter/img.jpg"));
// 这里演示
// 需要额外放入文字
// 而且需要放入2个图片
// 第一个图片靠左
// 第二个靠右 而且要额外的占用他后面的单元格
WriteCellData<Void> writeCellData = new WriteCellData<>();
imageDemoData.setWriteCellDataFile(writeCellData);
// 这里可以设置为 EMPTY 则代表不需要其他数据了
writeCellData.setType(CellDataTypeEnum.STRING);
writeCellData.setStringValue("额外的放一些文字");
// 可以放入多个图片
List<ImageData> imageDataList = new ArrayList<>();
ImageData imageData = new ImageData();
imageDataList.add(imageData);
writeCellData.setImageDataList(imageDataList);
// 放入2进制图片
imageData.setImage(FileUtils.readFileToByteArray(new File(imagePath)));
// 图片类型
imageData.setImageType(ImageType.PICTURE_TYPE_PNG);
// 上 右 下 左 需要留空
// 这个类似于 css 的 margin
// 这里实测 不能设置太大 超过单元格原始大小后 打开会提示修复。暂时未找到很好的解法。
imageData.setTop(5);
imageData.setRight(40);
imageData.setBottom(5);
imageData.setLeft(5);
// 放入第二个图片
imageData = new ImageData();
imageDataList.add(imageData);
writeCellData.setImageDataList(imageDataList);
imageData.setImage(FileUtils.readFileToByteArray(new File(imagePath)));
imageData.setImageType(ImageType.PICTURE_TYPE_PNG);
imageData.setTop(5);
imageData.setRight(5);
imageData.setBottom(5);
imageData.setLeft(50);
// 设置图片的位置 假设 现在目标 是 覆盖 当前单元格 和当前单元格右边的单元格
// 起点相对于当前单元格为0 当然可以不写
imageData.setRelativeFirstRowIndex(0);
imageData.setRelativeFirstColumnIndex(0);
imageData.setRelativeLastRowIndex(0);
// 前面3个可以不写 下面这个需要写 也就是 结尾 需要相对当前单元格 往右移动一格
// 也就是说 这个图片会覆盖当前单元格和 后面的那一格
imageData.setRelativeLastColumnIndex(1);
// 写入数据
EasyExcel.write(fileName, ImageDemoData.class).sheet().doWrite(list);
}
}
/**
* 超链接、备注、公式、指定单个单元格的样式、单个单元格多种样式
* <p>
* 1. 创建excel对应的实体对象 参照{@link WriteCellDemoData}
* <p>
* 2. 直接写即可
*
* @since 3.0.0-beta1
*/
@Test
public void writeCellDataWrite() {
String fileName = TestFileUtil.getPath() + "writeCellDataWrite" + System.currentTimeMillis() + ".xlsx";
WriteCellDemoData writeCellDemoData = new WriteCellDemoData();
// 设置超链接
WriteCellData<String> hyperlink = new WriteCellData<>("官方网站");
writeCellDemoData.setHyperlink(hyperlink);
HyperlinkData hyperlinkData = new HyperlinkData();
hyperlink.setHyperlinkData(hyperlinkData);
hyperlinkData.setAddress("https://github.com/alibaba/easyexcel");
hyperlinkData.setHyperlinkType(HyperlinkType.URL);
// 设置备注
WriteCellData<String> comment = new WriteCellData<>("备注的单元格信息");
writeCellDemoData.setCommentData(comment);
CommentData commentData = new CommentData();
comment.setCommentData(commentData);
commentData.setAuthor("Jiaju Zhuang");
commentData.setRichTextStringData(new RichTextStringData("这是一个备注"));
// 备注的默认大小是按照单元格的大小 这里想调整到4个单元格那么大 所以向后 向下 各额外占用了一个单元格
commentData.setRelativeLastColumnIndex(1);
commentData.setRelativeLastRowIndex(1);
// 设置公式
WriteCellData<String> formula = new WriteCellData<>();
writeCellDemoData.setFormulaData(formula);
FormulaData formulaData = new FormulaData();
formula.setFormulaData(formulaData);
// 将 123456789 中的第一个数字替换成 2
// 这里只是例子 如果真的涉及到公式 能内存算好尽量内存算好 公式能不用尽量不用
formulaData.setFormulaValue("REPLACE(123456789,1,1,2)");
// 设置单个单元格的样式 当然样式 很多的话 也可以用注解等方式。
WriteCellData<String> writeCellStyle = new WriteCellData<>("单元格样式");
writeCellStyle.setType(CellDataTypeEnum.STRING);
writeCellDemoData.setWriteCellStyle(writeCellStyle);
WriteCellStyle writeCellStyleData = new WriteCellStyle();
writeCellStyle.setWriteCellStyle(writeCellStyleData);
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.
writeCellStyleData.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
// 背景绿色
writeCellStyleData.setFillForegroundColor(IndexedColors.GREEN.getIndex());
// 设置单个单元格多种样式
// 这里需要设置 inMomery=true 不然会导致无法展示单个单元格多种样式,所以慎用
WriteCellData<String> richTest = new WriteCellData<>();
richTest.setType(CellDataTypeEnum.RICH_TEXT_STRING);
writeCellDemoData.setRichText(richTest);
RichTextStringData richTextStringData = new RichTextStringData();
richTest.setRichTextStringDataValue(richTextStringData);
richTextStringData.setTextString("红色绿色默认");
// 前2个字红色
WriteFont writeFont = new WriteFont();
writeFont.setColor(IndexedColors.RED.getIndex());
richTextStringData.applyFont(0, 2, writeFont);
// 接下来2个字绿色
writeFont = new WriteFont();
writeFont.setColor(IndexedColors.GREEN.getIndex());
richTextStringData.applyFont(2, 4, writeFont);
List<WriteCellDemoData> data = new ArrayList<>();
data.add(writeCellDemoData);
EasyExcel.write(fileName, WriteCellDemoData.class).inMemory(true).sheet("模板").doWrite(data);
}
/**
* 根据模板写入
* <p>
* 1. 创建excel对应的实体对象 参照{@link IndexData}
* <p>
* 2. 使用{@link ExcelProperty}注解指定写入的列
* <p>
* 3. 使用withTemplate 写取模板
* <p>
* 4. 直接写即可
*/
@Test
public void templateWrite() {
String templateFileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
String fileName = TestFileUtil.getPath() + "templateWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 这里要注意 withTemplate 的模板文件会全量存储在内存里面,所以尽量不要用于追加文件,如果文件模板文件过大会OOM
// 如果要再文件中追加(无法在一个线程里面处理,可以在一个线程的建议参照多次写入的demo) 建议临时存储到数据库 或者 磁盘缓存(ehcache) 然后再一次性写入
EasyExcel.write(fileName, DemoData.class).withTemplate(templateFileName).sheet().doWrite(data());
}
/**
* 列宽、行高
* <p>
* 1. 创建excel对应的实体对象 参照{@link WidthAndHeightData }
* <p>
* 2. 使用注解{@link ColumnWidth}、{@link HeadRowHeight}、{@link ContentRowHeight}指定宽度或高度
* <p>
* 3. 直接写即可
*/
@Test
public void widthAndHeightWrite() {
String fileName = TestFileUtil.getPath() + "widthAndHeightWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, WidthAndHeightData.class).sheet("模板").doWrite(data());
}
/**
* 注解形式自定义样式
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoStyleData}
* <p>
* 3. 直接写即可
*
* @since 2.2.0-beta1
*/
@Test
public void annotationStyleWrite() {
String fileName = TestFileUtil.getPath() + "annotationStyleWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoStyleData.class).sheet("模板").doWrite(data());
}
/**
* 拦截器形式自定义样式
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 创建一个style策略 并注册
* <p>
* 3. 直接写即可
*/
@Test
public void handlerStyleWrite() {
// 方法1 使用已有的策略 推荐
// HorizontalCellStyleStrategy 每一行的样式都一样 或者隔行一样
// AbstractVerticalCellStyleStrategy 每一列的样式都一样 需要自己回调每一页
String fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 背景设置为红色
headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short)20);
headWriteCellStyle.setWriteFont(headWriteFont);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
// 背景绿色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short)20);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoData.class)
.registerWriteHandler(horizontalCellStyleStrategy)
.sheet("模板")
.doWrite(data());
// 方法2: 使用easyexcel的方式完全自己写 不太推荐 尽量使用已有策略
// @since 3.0.0-beta2
fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, DemoData.class)
.registerWriteHandler(new CellWriteHandler() {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
// 当前事件会在 数据设置到poi的cell里面才会回调
// 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
if (BooleanUtils.isNotTrue(context.getHead())) {
// 第一个单元格
// 只要不是头 一定会有数据 当然fill的情况 可能要context.getCellDataList() ,这个需要看模板,因为一个单元格会有多个 WriteCellData
WriteCellData<?> cellData = context.getFirstCellData();
// 这里需要去cellData 获取样式
// 很重要的一个原因是 WriteCellStyle 和 dataFormatData绑定的 简单的说 比如你加了 DateTimeFormat
// ,已经将writeCellStyle里面的dataFormatData 改了 如果你自己new了一个WriteCellStyle,可能注解的样式就失效了
// 然后 getOrCreateStyle 用于返回一个样式,如果为空,则创建一个后返回
WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
// 这样样式就设置好了 后面有个FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到 cell里面去 所以可以不用管了
}
}
}).sheet("模板")
.doWrite(data());
// 方法3: 使用poi的样式完全自己写 不推荐
// @since 3.0.0-beta2
// 坑1:style里面有dataformat 用来格式化数据的 所以自己设置可能导致格式化注解不生效
// 坑2:不要一直去创建style 记得缓存起来 最多创建6W个就挂了
fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, DemoData.class)
.registerWriteHandler(new CellWriteHandler() {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
// 当前事件会在 数据设置到poi的cell里面才会回调
// 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
if (BooleanUtils.isNotTrue(context.getHead())) {
Cell cell = context.getCell();
// 拿到poi的workbook
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
// 不同单元格尽量传同一个 cellStyle
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
// 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
// cell里面去 会导致自己设置的不一样
context.getFirstCellData().setWriteCellStyle(null);
}
}
}).sheet("模板")
.doWrite(data());
}
/**
* 合并单元格
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData} {@link DemoMergeData}
* <p>
* 2. 创建一个merge策略 并注册
* <p>
* 3. 直接写即可
*
* @since 2.2.0-beta1
*/
@Test
public void mergeWrite() {
// 方法1 注解
String fileName = TestFileUtil.getPath() + "mergeWrite" + System.currentTimeMillis() + ".xlsx";
// 在DemoStyleData里面加上ContentLoopMerge注解
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoMergeData.class).sheet("模板").doWrite(data());
// 方法2 自定义合并单元格策略
fileName = TestFileUtil.getPath() + "mergeWrite" + System.currentTimeMillis() + ".xlsx";
// 每隔2行会合并 把eachColumn 设置成 3 也就是我们数据的长度,所以就第一列会合并。当然其他合并策略也可以自己写
LoopMergeStrategy loopMergeStrategy = new LoopMergeStrategy(2, 0);
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, DemoData.class).registerWriteHandler(loopMergeStrategy).sheet("模板").doWrite(data());
}
/**
* 使用table去写入
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 然后写入table即可
*/
@Test
public void tableWrite() {
String fileName = TestFileUtil.getPath() + "tableWrite" + System.currentTimeMillis() + ".xlsx";
// 方法1 这里直接写多个table的案例了,如果只有一个 也可以直一行代码搞定,参照其他案
// 这里 需要指定写用哪个class去写
try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
// 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了
WriteSheet writeSheet = EasyExcel.writerSheet("模板").needHead(Boolean.FALSE).build();
// 这里必须指定需要头,table 会继承sheet的配置,sheet配置了不需要,table 默认也是不需要
WriteTable writeTable0 = EasyExcel.writerTable(0).needHead(Boolean.TRUE).build();
WriteTable writeTable1 = EasyExcel.writerTable(1).needHead(Boolean.TRUE).build();
// 第一次写入会创建头
excelWriter.write(data(), writeSheet, writeTable0);
// 第二次写如也会创建头,然后在第一次的后面写入数据
excelWriter.write(data(), writeSheet, writeTable1);
}
}
/**
* 动态头,实时生成头写入
* <p>
* 思路是这样子的,先创建List<String>头格式的sheet仅仅写入头,然后通过table 不写入头的方式 去写入数据
*
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 然后写入table即可
*/
@Test
public void dynamicHeadWrite() {
String fileName = TestFileUtil.getPath() + "dynamicHeadWrite" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName)
// 这里放入动态头
.head(head()).sheet("模板")
// 当然这里数据也可以用 List<List<String>> 去传入
.doWrite(data());
}
/**
* 自动列宽(不太精确)
* <p>
* 这个目前不是很好用,比如有数字就会导致换行。而且长度也不是刚好和实际长度一致。 所以需要精确到刚好列宽的慎用。 当然也可以自己参照 {@link LongestMatchColumnWidthStyleStrategy}
* 重新实现.
* <p>
* poi 自带{@link SXSSFSheet#autoSizeColumn(int)} 对中文支持也不太好。目前没找到很好的算法。 有的话可以推荐下。
*
* <p>
* 1. 创建excel对应的实体对象 参照{@link LongestMatchColumnWidthData}
* <p>
* 2. 注册策略{@link LongestMatchColumnWidthStyleStrategy}
* <p>
* 3. 直接写即可
*/
@Test
public void longestMatchColumnWidthWrite() {
String fileName =
TestFileUtil.getPath() + "longestMatchColumnWidthWrite" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
EasyExcel.write(fileName, LongestMatchColumnWidthData.class)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("模板").doWrite(dataLong());
}
/**
* 下拉,超链接等自定义拦截器(上面几点都不符合但是要对单元格进行操作的参照这个)
* <p>
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | true |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/DemoData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/DemoData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomSheetWriteHandler.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomSheetWriteHandler.java | package com.alibaba.easyexcel.test.demo.write;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.util.CellRangeAddressList;
/**
* 自定义拦截器.对第一列第一行和第二行的数据新增下拉框,显示 测试1 测试2
*
* @author Jiaju Zhuang
*/
@Slf4j
public class CustomSheetWriteHandler implements SheetWriteHandler {
@Override
public void afterSheetCreate(SheetWriteHandlerContext context) {
log.info("第{}个Sheet写入成功。", context.getWriteSheetHolder().getSheetNo());
// 区间设置 第一列第一行和第二行的数据。由于第一行是头,所以第一、二行的数据实际上是第二三行
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 2, 0, 0);
DataValidationHelper helper = context.getWriteSheetHolder().getSheet().getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(new String[] {"测试1", "测试2"});
DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
context.getWriteSheetHolder().getSheet().addValidationData(dataValidation);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java | package com.alibaba.easyexcel.test.demo.write;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
/**
* String and string converter
*
* @author Jiaju Zhuang
*/
public class CustomStringStringConverter implements Converter<String> {
@Override
public Class<?> supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
/**
* 这里是读的时候会调用 不用管
*
* @return
*/
@Override
public String convertToJavaData(ReadConverterContext<?> context) {
return context.getReadCellData().getStringValue();
}
/**
* 这里是写的时候会调用 不用管
*
* @return
*/
@Override
public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
return new WriteCellData<>("自定义:" + context.getValue());
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/LongestMatchColumnWidthData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/LongestMatchColumnWidthData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class LongestMatchColumnWidthData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题很长日期标题很长日期标题很长很长")
private Date date;
@ExcelProperty("数字")
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java | package com.alibaba.easyexcel.test.demo.write;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Hyperlink;
/**
* 自定义拦截器。对第一行第一列的头超链接到:https://github.com/alibaba/easyexcel
*
* @author Jiaju Zhuang
*/
@Slf4j
public class CustomCellWriteHandler implements CellWriteHandler {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
Cell cell = context.getCell();
// 这里可以对cell进行任何操作
log.info("第{}行,第{}列写入完成。", cell.getRowIndex(), cell.getColumnIndex());
if (BooleanUtils.isTrue(context.getHead()) && cell.getColumnIndex() == 0) {
CreationHelper createHelper = context.getWriteSheetHolder().getSheet().getWorkbook().getCreationHelper();
Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL);
hyperlink.setAddress("https://github.com/alibaba/easyexcel");
cell.setHyperlink(hyperlink);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteCellDemoData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteCellDemoData.java | package com.alibaba.easyexcel.test.demo.write;
import com.alibaba.excel.metadata.data.WriteCellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 根据WriteCellData写
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class WriteCellDemoData {
/**
* 超链接
*
* @since 3.0.0-beta1
*/
private WriteCellData<String> hyperlink;
/**
* 备注
*
* @since 3.0.0-beta1
*/
private WriteCellData<String> commentData;
/**
* 公式
*
* @since 3.0.0-beta1
*/
private WriteCellData<String> formulaData;
/**
* 指定单元格的样式。当然样式 也可以用注解等方式。
*
* @since 3.0.0-beta1
*/
private WriteCellData<String> writeCellStyle;
/**
* 指定一个单元格有多个样式
*
* @since 3.0.0-beta1
*/
private WriteCellData<String> richText;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java | package com.alibaba.easyexcel.test.demo.write;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.converters.string.StringImageConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 图片导出类
*/
@Getter
@Setter
@EqualsAndHashCode
@ContentRowHeight(100)
@ColumnWidth(100 / 8)
public class ImageDataWithAnnotation {
private File file;
private InputStream inputStream;
/**
* 如果string类型 必须指定转换器,string默认转换成string
*/
@ExcelProperty(converter = StringImageConverter.class)
private String string;
private byte[] byteArray;
/**
* 根据url导出
*
* @since 2.1.1
*/
private URL url;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/DemoMergeData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/DemoMergeData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ContentLoopMerge;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 样式的数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
// 将第6-7行的2-3列合并成一个单元格
// @OnceAbsoluteMerge(firstRowIndex = 5, lastRowIndex = 6, firstColumnIndex = 1, lastColumnIndex = 2)
public class DemoMergeData {
// 这一列 每隔2行 合并单元格
@ContentLoopMerge(eachRow = 2)
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CommentWriteHandler.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/CommentWriteHandler.java | package com.alibaba.easyexcel.test.demo.write;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
/**
* 自定义拦截器.新增注释,第一行头加批注
*
* @author Jiaju Zhuang
*/
@Slf4j
public class CommentWriteHandler implements RowWriteHandler {
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
if (BooleanUtils.isTrue(context.getHead())) {
Sheet sheet = context.getWriteSheetHolder().getSheet();
Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
// 在第一行 第二列创建一个批注
Comment comment =
drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short)1, 0, (short)2, 1));
// 输入批注信息
comment.setString(new XSSFRichTextString("创建批注!"));
// 将批注添加到单元格对象中
sheet.getRow(0).getCell(1).setCellComment(comment);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDemoData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDemoData.java | package com.alibaba.easyexcel.test.demo.write;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.converters.string.StringImageConverter;
import com.alibaba.excel.metadata.data.WriteCellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 图片导出类
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@ContentRowHeight(100)
@ColumnWidth(100 / 8)
public class ImageDemoData {
private File file;
private InputStream inputStream;
/**
* 如果string类型 必须指定转换器,string默认转换成string
*/
@ExcelProperty(converter = StringImageConverter.class)
private String string;
private byte[] byteArray;
/**
* 根据url导出
*
* @since 2.1.1
*/
private URL url;
/**
* 根据文件导出 并设置导出的位置。
*
* @since 3.0.0-beta1
*/
private WriteCellData<Void> writeCellDataFile;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/DemoStyleData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/DemoStyleData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ContentFontStyle;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.annotation.write.style.HeadFontStyle;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.alibaba.excel.enums.poi.FillPatternTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 样式的数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
// 头背景设置成红色 IndexedColors.RED.getIndex()
@HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 10)
// 头字体设置成20
@HeadFontStyle(fontHeightInPoints = 20)
// 内容的背景设置成绿色 IndexedColors.GREEN.getIndex()
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 17)
// 内容字体设置成20
@ContentFontStyle(fontHeightInPoints = 20)
public class DemoStyleData {
// 字符串的头背景设置成粉红 IndexedColors.PINK.getIndex()
@HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 14)
// 字符串的头字体设置成20
@HeadFontStyle(fontHeightInPoints = 30)
// 字符串的内容的背景设置成天蓝 IndexedColors.SKY_BLUE.getIndex()
@ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
// 字符串的内容字体设置成20
@ContentFontStyle(fontHeightInPoints = 30)
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ConverterData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/write/ConverterData.java | package com.alibaba.easyexcel.test.demo.write;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类.这里的排序和excel里面的排序一致
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class ConverterData {
/**
* 我想所有的 字符串起前面加上"自定义:"三个字
*/
@ExcelProperty(value = "字符串标题", converter = CustomStringStringConverter.class)
private String string;
/**
* 我想写到excel 用年月日的格式
*/
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
@ExcelProperty("日期标题")
private Date date;
/**
* 我想写到excel 用百分比表示
*/
@NumberFormat("#.##%")
@ExcelProperty(value = "数字标题")
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/rare/WriteTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/rare/WriteTest.java | package com.alibaba.easyexcel.test.demo.rare;
import java.io.File;
import java.util.Date;
import java.util.List;
import com.alibaba.easyexcel.test.demo.write.DemoData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.jupiter.api.Test;
/**
* 记录一些不太常见的案例
*
* @author Jiaju Zhuang
*/
@Slf4j
public class WriteTest {
/**
* 压缩临时文件
* 在导出Excel且格式为xlsx的时候会生成一个临时的xml文件,会比较大,再磁盘不太够的情况下,可以压缩。
* 当然压缩式耗费性能的
*/
@Test
public void compressedTemporaryFile() {
log.info("临时的xml存储在:{}", FileUtils.getPoiFilesPath());
File file = TestFileUtil.createNewFile("rare/compressedTemporaryFile" + System.currentTimeMillis()
+ ".xlsx");
// 这里 需要指定写用哪个class去写
try (ExcelWriter excelWriter = EasyExcel.write(file, DemoData.class).registerWriteHandler(
new WorkbookWriteHandler() {
/**
* 拦截Workbook创建完成事件
* @param context
*/
@Override
public void afterWorkbookCreate(WorkbookWriteHandlerContext context) {
// 获取到Workbook对象
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
// 只有SXSSFWorkbook模式才会生成临时文件
if (workbook instanceof SXSSFWorkbook) {
SXSSFWorkbook sxssfWorkbook = (SXSSFWorkbook)workbook;
// 设置临时文件压缩,当然这个会浪费cpu性能 但是临时文件会变小
sxssfWorkbook.setCompressTempFiles(true);
}
}
}).build()) {
// 这里注意 如果同一个sheet只要创建一次
WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
// 10万数据 确保有足够的空间
for (int i = 0; i < 10000; i++) {
// 分页去数据库查询数据 这里可以去数据库查询每一页的数据
List<DemoData> data = data();
excelWriter.write(data, writeSheet);
}
log.info("写入完毕,开始准备迁移压缩文件。");
}
}
/**
* 在指定单元格写入数据
*/
@Test
public void specifiedCellWrite() {
File file = TestFileUtil.createNewFile("rare/specifiedCellWrite" + System.currentTimeMillis()
+ ".xlsx");
// 需要区分是在 最后一行之前 还是之后
// 区分的原因是:excel只能一直向前,而且内存里面只存储100条,而afterRowDispose是在每一行写入完成的时候调用,所以修改一行需要拦截这个事件
// 如果是在最后一行之后,由于后面不会再有数据了,所以只要拦截afterWorkbookDispose,在整个excel快写完的时候调用,继续写入数据即可
EasyExcel.write(file, DemoData.class)
// 写入的值在最后一行之前
.registerWriteHandler(new RowWriteHandler() {
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
if (context.getRow().getRowNum() == 2) {
Cell cell = context.getRow().getCell(2);
if (cell == null) {
cell = context.getRow().createCell(2);
}
cell.setCellValue("测试的第二行数据呀");
}
}
})
// 写入的值 在最后一一行之后
.registerWriteHandler(new WorkbookWriteHandler() {
@Override
public void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(99);
if (row == null) {
row = sheet.createRow(99);
}
Cell cell = row.getCell(2);
if (cell == null) {
cell = row.createCell(2);
}
cell.setCellValue("测试地99行数据呀");
}
})
.sheet("模板")
.doWrite(data());
log.info("写入到文件完成:{}", file);
}
private List<DemoData> data() {
List<DemoData> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setString("字符串" + i);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillData.java | package com.alibaba.easyexcel.test.demo.fill;
import java.util.Date;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class FillData {
private String name;
private double number;
private Date date;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java | package com.alibaba.easyexcel.test.demo.fill;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import org.junit.jupiter.api.Test;
/**
* 写的填充写法
*
* @author Jiaju Zhuang
* @since 2.1.1
*/
public class FillTest {
/**
* 最简单的填充
*
* @since 2.1.1
*/
@Test
public void simpleFill() {
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
String templateFileName =
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "simple.xlsx";
// 方案1 根据对象填充
String fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx";
// 这里 会填充到第一个sheet, 然后文件流会自动关闭
FillData fillData = new FillData();
fillData.setName("张三");
fillData.setNumber(5.2);
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(fillData);
// 方案2 根据Map填充
fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx";
// 这里 会填充到第一个sheet, 然后文件流会自动关闭
Map<String, Object> map = MapUtils.newHashMap();
map.put("name", "张三");
map.put("number", 5.2);
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(map);
}
/**
* 填充列表
*
* @since 2.1.1
*/
@Test
public void listFill() {
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
// 填充list 的时候还要注意 模板中{.} 多了个点 表示list
// 如果填充list的对象是map,必须包涵所有list的key,哪怕数据为null,必须使用map.put(key,null)
String templateFileName =
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "list.xlsx";
// 方案1 一下子全部放到内存里面 并填充
String fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx";
// 这里 会填充到第一个sheet, 然后文件流会自动关闭
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(data());
// 方案2 分多次 填充 会使用文件缓存(省内存)
fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx";
try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.fill(data(), writeSheet);
excelWriter.fill(data(), writeSheet);
}
}
/**
* 复杂的填充
*
* @since 2.1.1
*/
@Test
public void complexFill() {
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
// {} 代表普通变量 {.} 代表是list的变量
String templateFileName =
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complex.xlsx";
String fileName = TestFileUtil.getPath() + "complexFill" + System.currentTimeMillis() + ".xlsx";
// 方案1
try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
// 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。
// forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用
// 简单的说 如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
// 如果数据量大 list不是最后一行 参照下一个
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(data(), fillConfig, writeSheet);
excelWriter.fill(data(), fillConfig, writeSheet);
Map<String, Object> map = MapUtils.newHashMap();
map.put("date", "2019年10月9日13:28:28");
map.put("total", 1000);
excelWriter.fill(map, writeSheet);
}
}
/**
* 数据量大的复杂填充
* <p>
* 这里的解决方案是 确保模板list为最后一行,然后再拼接table.还有03版没救,只能刚正面加内存。
*
* @since 2.1.1
*/
@Test
public void complexFillWithTable() {
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
// {} 代表普通变量 {.} 代表是list的变量
// 这里模板 删除了list以后的数据,也就是统计的这一行
String templateFileName =
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complexFillWithTable.xlsx";
String fileName = TestFileUtil.getPath() + "complexFillWithTable" + System.currentTimeMillis() + ".xlsx";
// 方案1
try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
// 直接写入数据
excelWriter.fill(data(), writeSheet);
excelWriter.fill(data(), writeSheet);
// 写入list之前的数据
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "2019年10月9日13:28:28");
excelWriter.fill(map, writeSheet);
// list 后面还有个统计 想办法手动写入
// 这里偷懒直接用list 也可以用对象
List<List<String>> totalListList = ListUtils.newArrayList();
List<String> totalList = ListUtils.newArrayList();
totalListList.add(totalList);
totalList.add(null);
totalList.add(null);
totalList.add(null);
// 第四列
totalList.add("统计:1000");
// 这里是write 别和fill 搞错了
excelWriter.write(totalListList, writeSheet);
// 总体上写法比较复杂 但是也没有想到好的版本 异步的去写入excel 不支持行的删除和移动,也不支持备注这种的写入,所以也排除了可以
// 新建一个 然后一点点复制过来的方案,最后导致list需要新增行的时候,后面的列的数据没法后移,后续会继续想想解决方案
}
}
/**
* 横向的填充
*
* @since 2.1.1
*/
@Test
public void horizontalFill() {
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
// {} 代表普通变量 {.} 代表是list的变量
String templateFileName =
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "horizontal.xlsx";
String fileName = TestFileUtil.getPath() + "horizontalFill" + System.currentTimeMillis() + ".xlsx";
// 方案1
try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
excelWriter.fill(data(), fillConfig, writeSheet);
excelWriter.fill(data(), fillConfig, writeSheet);
Map<String, Object> map = new HashMap<>();
map.put("date", "2019年10月9日13:28:28");
excelWriter.fill(map, writeSheet);
}
}
/**
* 多列表组合填充填充
*
* @since 2.2.0-beta1
*/
@Test
public void compositeFill() {
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
// {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
String templateFileName =
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "composite.xlsx";
String fileName = TestFileUtil.getPath() + "compositeFill" + System.currentTimeMillis() + ".xlsx";
// 方案1
try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
// 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1,然后多个list必须用 FillWrapper包裹
excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet);
excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet);
excelWriter.fill(new FillWrapper("data2", data()), writeSheet);
excelWriter.fill(new FillWrapper("data2", data()), writeSheet);
excelWriter.fill(new FillWrapper("data3", data()), writeSheet);
excelWriter.fill(new FillWrapper("data3", data()), writeSheet);
Map<String, Object> map = new HashMap<String, Object>();
//map.put("date", "2019年10月9日13:28:28");
map.put("date", new Date());
excelWriter.fill(map, writeSheet);
}
}
private List<FillData> data() {
List<FillData> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
FillData fillData = new FillData();
list.add(fillData);
fillData.setName("张三");
fillData.setNumber(5.2);
fillData.setDate(new Date());
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ConverterDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ConverterDataListener.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 模板的读取类
*
* @author Jiaju Zhuang
*/
@Slf4j
public class ConverterDataListener implements ReadListener<ConverterData> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
private List<ConverterData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
@Override
public void invoke(ConverterData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
cachedDataList.add(data);
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExceptionListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExceptionListener.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 读取转换异常
*
* @author Jiaju Zhuang
*/
@Slf4j
public class DemoExceptionListener implements ReadListener<ExceptionDemoData> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
private List<ExceptionDemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
/**
* 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
*
* @param exception
* @param context
* @throws Exception
*/
@Override
public void onException(Exception exception, AnalysisContext context) {
log.error("解析失败,但是继续解析下一行:{}", exception.getMessage());
// 如果是某一个单元格的转换异常 能获取到具体行号
// 如果要获取头的信息 配合invokeHeadMap使用
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
log.error("第{}行,第{}列解析异常,数据为:{}", excelDataConvertException.getRowIndex(),
excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
}
}
/**
* 这里会一行行的返回头
*
* @param headMap
* @param context
*/
@Override
public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
}
@Override
public void invoke(ExceptionDemoData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoDAO.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoDAO.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
/**
* 假设这个是你的DAO存储。当然还要这个类让spring管理,当然你不用需要存储,也不需要这个类。
*
* @author Jiaju Zhuang
**/
public class DemoDAO {
public void save(List<DemoData> list) {
// 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataReadDemoData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataReadDemoData.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.Date;
import com.alibaba.excel.metadata.data.CellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类.这里的排序和excel里面的排序一致
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class CellDataReadDemoData {
private CellData<String> string;
// 这里注意 虽然是日期 但是 类型 存储的是number 因为excel 存储的就是number
private CellData<Date> date;
private CellData<Double> doubleData;
// 这里并不一定能完美的获取 有些公式是依赖性的 可能会读不到 这个问题后续会修复
private CellData<String> formulaValue;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataDemoHeadDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataDemoHeadDataListener.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 读取头
*
* @author Jiaju Zhuang
*/
@Slf4j
public class CellDataDemoHeadDataListener implements ReadListener<CellDataReadDemoData> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 100;
private List<CellDataReadDemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
@Override
public void invoke(CellDataReadDemoData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoData.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.Date;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类.这里的排序和excel里面的排序一致
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class DemoData {
private String string;
private Date date;
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java | package com.alibaba.easyexcel.test.demo.read;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
/**
* String and string converter
*
* @author Jiaju Zhuang
*/
public class CustomStringStringConverter implements Converter<String> {
@Override
public Class<?> supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
/**
* 这里读的时候会调用
*
* @param context
* @return
*/
@Override
public String convertToJavaData(ReadConverterContext<?> context) {
return "自定义:" + context.getReadCellData().getStringValue();
}
/**
* 这里是写的时候会调用 不用管
*
* @return
*/
@Override
public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
return new WriteCellData<>(context.getValue());
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraListener.java | package com.alibaba.easyexcel.test.demo.read;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
/**
* 读取单元格的批注
*
* @author Jiaju Zhuang
**/
@Slf4j
public class DemoExtraListener implements ReadListener<DemoExtraData> {
@Override
public void invoke(DemoExtraData data, AnalysisContext context) {}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {}
@Override
public void extra(CellExtra extra, AnalysisContext context) {
log.info("读取到了一条额外信息:{}", JSON.toJSONString(extra));
switch (extra.getType()) {
case COMMENT:
log.info("额外信息是批注,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(),
extra.getColumnIndex(),
extra.getText());
break;
case HYPERLINK:
if ("Sheet1!A1".equals(extra.getText())) {
log.info("额外信息是超链接,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(),
extra.getColumnIndex(), extra.getText());
} else if ("Sheet2!A1".equals(extra.getText())) {
log.info(
"额外信息是超链接,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{},"
+ "内容是:{}",
extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
extra.getLastColumnIndex(), extra.getText());
} else {
Assertions.fail("Unknown hyperlink!");
}
break;
case MERGE:
log.info(
"额外信息是合并单元格,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}",
extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
extra.getLastColumnIndex());
break;
default:
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ReadTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ReadTest.java | package com.alibaba.easyexcel.test.demo.read;
import java.io.File;
import java.util.List;
import java.util.Map;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.DefaultConverterLoader;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
/**
* 读的常见写法
*
* @author Jiaju Zhuang
*/
@Slf4j
public class ReadTest {
/**
* 最简单的读
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoDataListener}
* <p>
* 3. 直接读即可
*/
@Test
public void simpleRead() {
// 写法1:JDK8+ ,不用额外写一个DemoDataListener
// since: 3.0.0-beta1
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
// 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行
// 具体需要返回多少行可以在`PageReadListener`的构造函数设置
EasyExcel.read(fileName, DemoData.class, new PageReadListener<DemoData>(dataList -> {
for (DemoData demoData : dataList) {
log.info("读取到一条数据{}", JSON.toJSONString(demoData));
}
})).sheet().doRead();
// 写法2:
// 匿名内部类 不用额外写一个DemoDataListener
fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
EasyExcel.read(fileName, DemoData.class, new ReadListener<DemoData>() {
/**
* 单次缓存的数据量
*/
public static final int BATCH_COUNT = 100;
/**
*临时存储
*/
private List<DemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
@Override
public void invoke(DemoData data, AnalysisContext context) {
cachedDataList.add(data);
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
log.info("存储数据库成功!");
}
}).sheet().doRead();
// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
// 写法3:
fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();
// 写法4
fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 一个文件一个reader
try (ExcelReader excelReader = EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).build()) {
// 构建一个sheet 这里可以指定名字或者no
ReadSheet readSheet = EasyExcel.readSheet(0).build();
// 读取一个sheet
excelReader.read(readSheet);
}
}
/**
* 指定列的下标或者列名
*
* <p>
* 1. 创建excel对应的实体对象,并使用{@link ExcelProperty}注解. 参照{@link IndexOrNameData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link IndexOrNameDataListener}
* <p>
* 3. 直接读即可
*/
@Test
public void indexOrNameRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里默认读取第一个sheet
EasyExcel.read(fileName, IndexOrNameData.class, new IndexOrNameDataListener()).sheet().doRead();
}
/**
* 读多个或者全部sheet,这里注意一个sheet不能读取多次,多次读取需要重新读取文件
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoDataListener}
* <p>
* 3. 直接读即可
*/
@Test
public void repeatedRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 读取全部sheet
// 这里需要注意 DemoDataListener的doAfterAllAnalysed 会在每个sheet读取完毕后调用一次。然后所有sheet都会往同一个DemoDataListener里面写
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).doReadAll();
// 读取部分sheet
fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 写法1
try (ExcelReader excelReader = EasyExcel.read(fileName).build()) {
// 这里为了简单 所以注册了 同样的head 和Listener 自己使用功能必须不同的Listener
ReadSheet readSheet1 =
EasyExcel.readSheet(0).head(DemoData.class).registerReadListener(new DemoDataListener()).build();
ReadSheet readSheet2 =
EasyExcel.readSheet(1).head(DemoData.class).registerReadListener(new DemoDataListener()).build();
// 这里注意 一定要把sheet1 sheet2 一起传进去,不然有个问题就是03版的excel 会读取多次,浪费性能
excelReader.read(readSheet1, readSheet2);
}
}
/**
* 日期、数字或者自定义格式转换
* <p>
* 默认读的转换器{@link DefaultConverterLoader#loadDefaultReadConverter()}
* <p>
* 1. 创建excel对应的实体对象 参照{@link ConverterData}.里面可以使用注解{@link DateTimeFormat}、{@link NumberFormat}或者自定义注解
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link ConverterDataListener}
* <p>
* 3. 直接读即可
*/
@Test
public void converterRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet
EasyExcel.read(fileName, ConverterData.class, new ConverterDataListener())
// 这里注意 我们也可以registerConverter来指定自定义转换器, 但是这个转换变成全局了, 所有java为string,excel为string的都会用这个转换器。
// 如果就想单个字段使用请使用@ExcelProperty 指定converter
// .registerConverter(new CustomStringStringConverter())
// 读取sheet
.sheet().doRead();
}
/**
* 多行头
*
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoDataListener}
* <p>
* 3. 设置headRowNumber参数,然后读。 这里要注意headRowNumber如果不指定, 会根据你传入的class的{@link ExcelProperty#value()}里面的表头的数量来决定行数,
* 如果不传入class则默认为1.当然你指定了headRowNumber不管是否传入class都是以你传入的为准。
*/
@Test
public void complexHeaderRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet()
// 这里可以设置1,因为头就是一行。如果多行头,可以设置其他值。不传入也可以,因为默认会根据DemoData 来解析,他没有指定头,也就是默认1行
.headRowNumber(1).doRead();
}
/**
* 读取表头数据
*
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoHeadDataListener}
* <p>
* 3. 直接读即可
*/
@Test
public void headerRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet
EasyExcel.read(fileName, DemoData.class, new DemoHeadDataListener()).sheet().doRead();
}
/**
* 额外信息(批注、超链接、合并单元格信息读取)
* <p>
* 由于是流式读取,没法在读取到单元格数据的时候直接读取到额外信息,所以只能最后通知哪些单元格有哪些额外信息
*
* <p>
* 1. 创建excel对应的实体对象 参照{@link DemoExtraData}
* <p>
* 2. 由于默认异步读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoExtraListener}
* <p>
* 3. 直接读即可
*
* @since 2.2.0-beat1
*/
@Test
public void extraRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "extra.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet
EasyExcel.read(fileName, DemoExtraData.class, new DemoExtraListener())
// 需要读取批注 默认不读取
.extraRead(CellExtraTypeEnum.COMMENT)
// 需要读取超链接 默认不读取
.extraRead(CellExtraTypeEnum.HYPERLINK)
// 需要读取合并单元格信息 默认不读取
.extraRead(CellExtraTypeEnum.MERGE).sheet().doRead();
}
/**
* 读取公式和单元格类型
*
* <p>
* 1. 创建excel对应的实体对象 参照{@link CellDataReadDemoData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoHeadDataListener}
* <p>
* 3. 直接读即可
*
* @since 2.2.0-beat1
*/
@Test
public void cellDataRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "cellDataDemo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet
EasyExcel.read(fileName, CellDataReadDemoData.class, new CellDataDemoHeadDataListener()).sheet().doRead();
}
/**
* 数据转换等异常处理
*
* <p>
* 1. 创建excel对应的实体对象 参照{@link ExceptionDemoData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoExceptionListener}
* <p>
* 3. 直接读即可
*/
@Test
public void exceptionRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet
EasyExcel.read(fileName, ExceptionDemoData.class, new DemoExceptionListener()).sheet().doRead();
}
/**
* 同步的返回,不推荐使用,如果数据量大会把数据放到内存里面
*/
@Test
public void synchronousRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 同步读取会自动finish
List<DemoData> list = EasyExcel.read(fileName).head(DemoData.class).sheet().doReadSync();
for (DemoData data : list) {
log.info("读取到数据:{}", JSON.toJSONString(data));
}
// 这里 也可以不指定class,返回一个list,然后读取第一个sheet 同步读取会自动finish
List<Map<Integer, String>> listMap = EasyExcel.read(fileName).sheet().doReadSync();
for (Map<Integer, String> data : listMap) {
// 返回每条数据的键值对 表示所在的列 和所在列的值
log.info("读取到数据:{}", JSON.toJSONString(data));
}
}
/**
* 不创建对象的读
*/
@Test
public void noModelRead() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
// 这里 只要,然后读取第一个sheet 同步读取会自动finish
EasyExcel.read(fileName, new NoModelDataListener()).sheet().doRead();
}
/**
* 自定义修改csv配置
*/
@Test
public void csvFormat() {
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.csv";
try (ExcelReader excelReader = EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).build()) {
// 判断是 csv 文件
if (excelReader.analysisContext().readWorkbookHolder() instanceof CsvReadWorkbookHolder) {
CsvReadWorkbookHolder csvReadWorkbookHolder = (CsvReadWorkbookHolder)excelReader.analysisContext()
.readWorkbookHolder();
// 设置成逗号分隔 当然默认也是逗号分隔
// 这里要注意 withDelimiter 会重新生成一个 所以要放回去
csvReadWorkbookHolder.setCsvFormat(csvReadWorkbookHolder.getCsvFormat().withDelimiter(','));
}
// 拿到所有 sheet
List<ReadSheet> readSheetList = excelReader.excelExecutor().sheetList();
// 如果只想读取第一个 咋样传入参数即可
//ReadSheet readSheet = EasyExcel.readSheet(0).build();
excelReader.read(readSheetList);
}
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ExceptionDemoData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ExceptionDemoData.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.Date;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类.这里的排序和excel里面的排序一致
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class ExceptionDemoData {
/**
* 用日期去接字符串 肯定报错
*/
private Date date;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoDataListener.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 模板的读取类
*
* @author Jiaju Zhuang
*/
// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
public class DemoDataListener implements ReadListener<DemoData> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 100;
/**
* 缓存的数据
*/
private List<DemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
/**
* 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
*/
private DemoDAO demoDAO;
public DemoDataListener() {
// 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
demoDAO = new DemoDAO();
}
/**
* 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
*
* @param demoDAO
*/
public DemoDataListener(DemoDAO demoDAO) {
this.demoDAO = demoDAO;
}
/**
* 这个每一条数据解析都会来调用
*
* @param data one row value. It is same as {@link AnalysisContext#readRowHolder()}
* @param context
*/
@Override
public void invoke(DemoData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
cachedDataList.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
/**
* 所有数据解析完成了 都会来调用
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
demoDAO.save(cachedDataList);
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/NoModelDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/NoModelDataListener.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 直接用map接收数据
*
* @author Jiaju Zhuang
*/
@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
@Override
public void invoke(Map<Integer, String> data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
cachedDataList.add(data);
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/IndexOrNameDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/IndexOrNameDataListener.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 模板的读取类
*
* @author Jiaju Zhuang
*/
@Slf4j
public class IndexOrNameDataListener extends AnalysisEventListener<IndexOrNameData> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
private List<IndexOrNameData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
@Override
public void invoke(IndexOrNameData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
cachedDataList.add(data);
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoHeadDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoHeadDataListener.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 读取头
*
* @author Jiaju Zhuang
*/
@Slf4j
public class DemoHeadDataListener implements ReadListener<DemoData> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
private List<ExceptionDemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
/**
* 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
*
* @param exception
* @param context
* @throws Exception
*/
@Override
public void onException(Exception exception, AnalysisContext context) {
log.error("解析失败,但是继续解析下一行:{}", exception.getMessage());
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
log.error("第{}行,第{}列解析异常,数据为:{}", excelDataConvertException.getRowIndex(),
excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
}
}
/**
* 这里会一行行的返回头
*
* @param headMap
* @param context
*/
@Override
public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
// 如果想转成成 Map<Integer,String>
// 方案1: 不要implements ReadListener 而是 extends AnalysisEventListener
// 方案2: 调用 ConverterUtils.convertToStringMap(headMap, context) 自动会转换
}
@Override
public void invoke(DemoData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/IndexOrNameData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/IndexOrNameData.java | package com.alibaba.easyexcel.test.demo.read;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class IndexOrNameData {
/**
* 强制读取第三个 这里不建议 index 和 name 同时用,要么一个对象只用index,要么一个对象只用name去匹配
*/
@ExcelProperty(index = 2)
private Double doubleData;
/**
* 用名字去匹配,这里需要注意,如果名字重复,会导致只有一个字段读取到数据
*/
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraData.java | package com.alibaba.easyexcel.test.demo.read;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class DemoExtraData {
private String row1;
private String row2;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ConverterData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/read/ConverterData.java | package com.alibaba.easyexcel.test.demo.read;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类.这里的排序和excel里面的排序一致
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class ConverterData {
/**
* 我自定义 转换器,不管数据库传过来什么 。我给他加上“自定义:”
*/
@ExcelProperty(converter = CustomStringStringConverter.class)
private String string;
/**
* 这里用string 去接日期才能格式化。我想接收年月日格式
*/
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
private String date;
/**
* 我想接收百分比的数字
*/
@NumberFormat("#.##%")
private String doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java | package com.alibaba.easyexcel.test.demo.web;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
/**
* web读写案例
*
* @author Jiaju Zhuang
**/
@Controller
public class WebTest {
@Autowired
private UploadDAO uploadDAO;
/**
* 文件下载(失败了会返回一个有部分数据的Excel)
* <p>
* 1. 创建excel对应的实体对象 参照{@link DownloadData}
* <p>
* 2. 设置返回的 参数
* <p>
* 3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
*/
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
}
/**
* 文件下载并且失败的时候返回json(默认失败了会返回一个有部分数据的Excel)
*
* @since 2.1.1
*/
@GetMapping("downloadFailedUsingJson")
public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 这里需要设置不关闭流
EasyExcel.write(response.getOutputStream(), DownloadData.class).autoCloseStream(Boolean.FALSE).sheet("模板")
.doWrite(data());
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = MapUtils.newHashMap();
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}
/**
* 文件上传
* <p>
* 1. 创建excel对应的实体对象 参照{@link UploadData}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link UploadDataListener}
* <p>
* 3. 直接读即可
*/
@PostMapping("upload")
@ResponseBody
public String upload(MultipartFile file) throws IOException {
EasyExcel.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDAO)).sheet().doRead();
return "success";
}
private List<DownloadData> data() {
List<DownloadData> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
DownloadData data = new DownloadData();
data.setString("字符串" + 0);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/UploadData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/UploadData.java | package com.alibaba.easyexcel.test.demo.web;
import java.util.Date;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class UploadData {
private String string;
private Date date;
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/EasyexcelApplication.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/EasyexcelApplication.java | package com.alibaba.easyexcel.test.demo.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EasyexcelApplication {
public static void main(String[] args) {
SpringApplication.run(EasyexcelApplication.class, args);
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/UploadDAO.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/UploadDAO.java | package com.alibaba.easyexcel.test.demo.web;
import java.util.List;
import org.springframework.stereotype.Repository;
/**
* 假设这个是你的DAO存储。当然还要这个类让spring管理,当然你不用需要存储,也不需要这个类。
*
* @author Jiaju Zhuang
**/
@Repository
public class UploadDAO {
public void save(List<UploadData> list) {
// 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/DownloadData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/DownloadData.java | package com.alibaba.easyexcel.test.demo.web;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 基础数据类
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class DownloadData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/UploadDataListener.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/demo/web/UploadDataListener.java | package com.alibaba.easyexcel.test.demo.web;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
/**
* 模板的读取类
*
* @author Jiaju Zhuang
*/
// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
public class UploadDataListener implements ReadListener<UploadData> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
private List<UploadData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
/**
* 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
*/
private UploadDAO uploadDAO;
public UploadDataListener() {
// 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
uploadDAO = new UploadDAO();
}
/**
* 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
*
* @param uploadDAO
*/
public UploadDataListener(UploadDAO uploadDAO) {
this.uploadDAO = uploadDAO;
}
/**
* 这个每一条数据解析都会来调用
*
* @param data one row value. It is same as {@link AnalysisContext#readRowHolder()}
* @param context
*/
@Override
public void invoke(UploadData data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
cachedDataList.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
/**
* 所有数据解析完成了 都会来调用
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", cachedDataList.size());
uploadDAO.save(cachedDataList);
log.info("存储数据库成功!");
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/WriteLargeTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/WriteLargeTest.java | package com.alibaba.easyexcel.test.temp;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.easyexcel.test.core.large.LargeData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import lombok.extern.slf4j.Slf4j;
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.record.BOFRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 临时测试
*
* @author Jiaju Zhuang
**/
@Slf4j
public class WriteLargeTest {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteLargeTest.class);
@Test
public void test() throws Exception {
// 方法2 如果写到不同的sheet 同一个对象
String fileName = TestFileUtil.getPath() + "large" + System.currentTimeMillis() + ".xlsx";
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 背景设置为红色
headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short)20);
headWriteCellStyle.setWriteFont(headWriteFont);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
// 背景绿色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short)20);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
ExcelWriter excelWriter = EasyExcel.write(fileName, LargeData.class).registerWriteHandler(
horizontalCellStyleStrategy).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
for (int j = 0; j < 100; j++) {
excelWriter.write(data(), writeSheet);
LOGGER.info("{} fill success.", j);
}
excelWriter.finish();
}
@Test
public void read() throws Exception {
log.info("start");
String fileName = "/Users/zhuangjiaju/Downloads/1e9e0578a9634abbbbd9b67f338f142a.xls";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
// 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行
// 具体需要返回多少行可以在`PageReadListener`的构造函数设置
EasyExcel.read(fileName, new PageReadListener<List<Map<String, String>>>(dataList -> {
log.info("SIZEL:{}", dataList.size());
})).sheet().doRead();
log.info("test");
}
@Test
public void read2() throws Exception {
// 使用输入的文件创建一个新的文件输入流
//FileInputStream fin = new FileInputStream("/Users/zhuangjiaju/Downloads/1e9e0578a9634abbbbd9b67f338f142a
// .xls");
// 创建一个新的org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = new POIFSFileSystem(
new File("/Users/zhuangjiaju/Downloads/1e9e0578a9634abbbbd9b67f338f142a.xls"));
// 在InputStream中获取Workbook流
InputStream din = poifs.createDocumentInputStream("Workbook");
// 构造出HSSFRequest对象
HSSFRequest req = new HSSFRequest();
// 注册全部的监听器
req.addListenerForAllRecords(new EventExample());
// 创建事件工厂
HSSFEventFactory factory = new HSSFEventFactory();
// 根据文档输入流处理我们监听的事件
factory.processEvents(req, din);
// 关闭文件输入流
//fin.close();
// 关闭文档输入流
din.close();
System.out.println("读取结束");
}
@Test
public void read3() throws Exception {
HSSFWorkbook hwb = new HSSFWorkbook(
new FileInputStream("/Users/zhuangjiaju/Downloads/1e9e0578a9634abbbbd9b67f338f142a.xls"));
HSSFSheet sheet = hwb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if(row!=null){
log.info("r:{}",row.getRowNum());
}
}
log.info("end");
}
public static class EventExample implements HSSFListener {
private SSTRecord sstrec;
/**
* 此方法监听传入记录并根据需要处理它们
*
* @param record读取时找到的记录
*/
public void processRecord(Record record) {
switch (record.getSid()) {
//BOFRecord可以表示工作表或工作簿的开头
case BOFRecord.sid:
BOFRecord bof = (BOFRecord)record;
if (bof.getType() == bof.TYPE_WORKBOOK) {
System.out.println("监听到工作表");
} else if (bof.getType() == bof.TYPE_WORKSHEET) {
System.out.println("监听到工作簿");
}
break;
case BoundSheetRecord.sid:
BoundSheetRecord bsr = (BoundSheetRecord)record;
System.out.println("工作簿名称: " + bsr.getSheetname());
break;
}
}
}
@Test
public void test2() throws Exception {
// 方法2 如果写到不同的sheet 同一个对象
String fileName = TestFileUtil.getPath() + "large" + System.currentTimeMillis() + ".xlsx";
ExcelWriter excelWriter = EasyExcel.write(fileName, LargeData.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
for (int j = 0; j < 100; j++) {
excelWriter.write(data(), writeSheet);
LOGGER.info("{} fill success.", j);
}
excelWriter.finish();
}
private List<List<String>> data() {
List<List<String>> list = new ArrayList<>();
for (int j = 0; j < 10000; j++) {
List<String> oneRow = new ArrayList<>();
for (int i = 0; i < 150; i++) {
oneRow.add("这是测试字段" + i);
}
list.add(oneRow);
}
return list;
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/StyleData.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/StyleData.java | package com.alibaba.easyexcel.test.temp;
import java.util.List;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class StyleData {
private byte[] byteValue;
private Byte[] byteValue2;
private byte byteValue1;
private Byte byteValue4;
private byte byteValue3;
private String[] ss;
private List<String> s1s;
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/StyleTest.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/StyleTest.java | package com.alibaba.easyexcel.test.temp;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.ExcelStyleDateFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 临时测试
*
* @author Jiaju Zhuang
**/
public class StyleTest {
private static final Logger LOGGER = LoggerFactory.getLogger(StyleTest.class);
@Test
public void test() {
List<Object> list = EasyExcel.read("D:\\test\\styleTest.xls").sheet().headRowNumber(0).doReadSync();
for (Object data : list) {
LOGGER.info("返回数据:{}", JSON.toJSONString(data));
}
}
@Test
public void poi() throws Exception {
InputStream is = new FileInputStream("D:\\test\\styleTest.xls");
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
HSSFRow hssfRow = hssfSheet.getRow(0);
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
DataFormatter formatter = new DataFormatter();
System.out.println(hssfRow.getCell(0).getNumericCellValue());
System.out.println(hssfRow.getCell(1).getNumericCellValue());
System.out.println(hssfRow.getCell(2).getNumericCellValue());
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(1).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(2).getCellStyle().getDataFormatString());
}
@Test
public void poi07() throws Exception {
InputStream is = new FileInputStream("D:\\test\\styleTest.xlsx");
Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel 2003/2007/2010 都是可以处理的
Sheet sheet = workbook.getSheetAt(0);
Row hssfRow = sheet.getRow(0);
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
DataFormatter formatter = new DataFormatter();
System.out.println(hssfRow.getCell(0).getNumericCellValue());
System.out.println(hssfRow.getCell(1).getNumericCellValue());
System.out.println(hssfRow.getCell(2).getNumericCellValue());
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(1).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(2).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(3).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(1).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(2).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(3).getCellStyle().getDataFormatString());
isDate(hssfRow.getCell(0));
isDate(hssfRow.getCell(1));
isDate(hssfRow.getCell(2));
isDate(hssfRow.getCell(3));
}
@Test
public void poi0701() throws Exception {
InputStream is = new FileInputStream("D:\\test\\f1.xlsx");
Workbook workbook = WorkbookFactory.create(is);
Sheet sheet = workbook.getSheetAt(0);
print(sheet.getRow(0).getCell(0));
print(sheet.getRow(1).getCell(0));
print(sheet.getRow(2).getCell(0));
print(sheet.getRow(3).getCell(0));
}
@Test
public void poi0702() throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("D:\\test\\t2.xlsx"));
workbook = WorkbookFactory.create(new File("D:\\test\\t2.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
System.out.println(row.getCell(0).getNumericCellValue());
}
@Test
public void poi0703() throws Exception {
try {
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream("D:\\test\\t2.xlsx"));
System.out.println(poifsFileSystem.getRoot().hasEntry(Decryptor.DEFAULT_POIFS_ENTRY));
} catch (Exception e) {
e.printStackTrace();
}
try {
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new File("D:\\test\\t2.xlsx"));
System.out.println(poifsFileSystem.getRoot().hasEntry(Decryptor.DEFAULT_POIFS_ENTRY));
} catch (Exception e) {
e.printStackTrace();
}
try {
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream("D:\\test\\t222.xlsx"));
System.out.println(poifsFileSystem.getRoot().hasEntry(Decryptor.DEFAULT_POIFS_ENTRY));
} catch (Exception e) {
e.printStackTrace();
}
try {
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new File("D:\\test\\t222.xlsx"));
System.out.println(poifsFileSystem.getRoot().hasEntry(Decryptor.DEFAULT_POIFS_ENTRY));
} catch (Exception e) {
e.printStackTrace();
}
}
private void print(Cell cell) {
System.out.println(
DateUtil.isADateFormat(cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString()));
System.out.println(cell.getCellStyle().getDataFormat());
System.out.println(cell.getCellStyle().getDataFormatString());
DataFormatter f = new DataFormatter();
System.out.println(f.formatCellValue(cell));
if (cell.getCellStyle().getDataFormatString() != null) {
}
ExcelStyleDateFormatter ff = new ExcelStyleDateFormatter(cell.getCellStyle().getDataFormatString());
}
@Test
public void testFormatter() throws Exception {
ExcelStyleDateFormatter ff = new ExcelStyleDateFormatter("yyyy年m月d日");
System.out.println(ff.format(new Date()));
}
@Test
public void testFormatter2() throws Exception {
StyleData styleData = new StyleData();
Field field = styleData.getClass().getDeclaredField("byteValue");
LOGGER.info("field:{}", field.getType().getName());
field = styleData.getClass().getDeclaredField("byteValue2");
LOGGER.info("field:{}", field.getType().getName());
field = styleData.getClass().getDeclaredField("byteValue4");
LOGGER.info("field:{}", field.getType());
field = styleData.getClass().getDeclaredField("byteValue3");
LOGGER.info("field:{}", field.getType());
}
@Test
public void testFormatter3() throws Exception {
LOGGER.info("field:{}", Byte.class == Byte.class);
}
private void isDate(Cell cell) {
System.out.println(
DateUtil.isADateFormat(cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString()));
//System.out.println(HSSFDateUtil.isCellDateFormatted(cell));
DataFormatter f = new DataFormatter();
System.out.println(f.formatCellValue(cell));
}
@Test
public void testBuiltinFormats() throws Exception {
System.out.println(BuiltinFormats.getBuiltinFormat(48));
System.out.println(BuiltinFormats.getBuiltinFormat(57));
System.out.println(BuiltinFormats.getBuiltinFormat(28));
}
}
| java | Apache-2.0 | aae9c61ab603c04331333782eedd2896d7bc5386 | 2026-01-04T14:46:28.604473Z | false |
alibaba/easyexcel | https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java | easyexcel-test/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java | package com.alibaba.easyexcel.test.temp;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.alibaba.easyexcel.test.demo.write.DemoData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.BooleanUtils;
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.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 临时测试
*
* @author Jiaju Zhuang
**/
public class WriteV33Test {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteV33Test.class);
@Test
public void handlerStyleWrite() {
// 方法1 使用已有的策略 推荐
// HorizontalCellStyleStrategy 每一行的样式都一样 或者隔行一样
// AbstractVerticalCellStyleStrategy 每一列的样式都一样 需要自己回调每一页
String fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
//// 头的策略
//WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//// 背景设置为红色
//headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
//WriteFont headWriteFont = new WriteFont();
//headWriteFont.setFontHeightInPoints((short)20);
//headWriteCellStyle.setWriteFont(headWriteFont);
//// 内容的策略
//WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
//contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//// 背景绿色
//contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
//WriteFont contentWriteFont = new WriteFont();
//// 字体大小
//contentWriteFont.setFontHeightInPoints((short)20);
//contentWriteCellStyle.setWriteFont(contentWriteFont);
//// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
//HorizontalCellStyleStrategy horizontalCellStyleStrategy =
// new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
//
//// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
//EasyExcel.write(fileName, DemoData.class)
// .registerWriteHandler(horizontalCellStyleStrategy)
// .sheet("模板")
// .doWrite(data());
//
// 方法2: 使用easyexcel的方式完全自己写 不太推荐 尽量使用已有策略
//fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
//EasyExcel.write(fileName, DemoData.class)
// .registerWriteHandler(new CellWriteHandler() {
// @Override
// public void afterCellDispose(CellWriteHandlerContext context) {
// // 当前事件会在 数据设置到poi的cell里面才会回调
// // 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
// if (BooleanUtils.isNotTrue(context.getHead())) {
// // 第一个单元格
// // 只要不是头 一定会有数据 当然fill的情况 可能要context.getCellDataList() ,这个需要看模板,因为一个单元格会有多个 WriteCellData
// WriteCellData<?> cellData = context.getFirstCellData();
// // 这里需要去cellData 获取样式
// // 很重要的一个原因是 WriteCellStyle 和 dataFormatData绑定的 简单的说 比如你加了 DateTimeFormat
// // ,已经将writeCellStyle里面的dataFormatData 改了 如果你自己new了一个WriteCellStyle,可能注解的样式就失效了
// // 然后 getOrCreateStyle 用于返回一个样式,如果为空,则创建一个后返回
// WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
// writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
// // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
// writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//
// // 这样样式就设置好了 后面有个FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到 cell里面去 所以可以不用管了
// }
// }
// }).sheet("模板")
// .doWrite(data());
// 方法3: 使用poi的样式完全自己写 不推荐
// 坑1:style里面有dataformat 用来格式化数据的 所以自己设置可能导致格式化注解不生效
// 坑2:不要一直去创建style 记得缓存起来 最多创建6W个就挂了
fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, DemoData.class)
.registerWriteHandler(new CellWriteHandler() {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
// 当前事件会在 数据设置到poi的cell里面才会回调
// 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
if (BooleanUtils.isNotTrue(context.getHead())) {
Cell cell = context.getCell();
// 拿到poi的workbook
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
// 不同单元格尽量传同一个 cellStyle
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
// 由于这里没有指定datafrmat 所以格式化出来的数据需要
// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
// cell里面去 会导致自己设置的不一样
context.getFirstCellData().setWriteCellStyle(null);
}
}
}).sheet("模板")
.doWrite(data());
}
private List<DemoData> data() {
List<DemoData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setString("字符串" + i);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
@Test
public void test4() throws Exception{
Path path= Files.createTempFile(new File("/Users/zhuangjiaju/test/test0422/test/xx").toPath(),System.currentTimeMillis()+"",".jpg");
System.out.println(path);
}
}
| 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.