提交 a9b2f480 编写于 作者: Z zhuangjiaju

优化读写逻辑

上级 1026a18b
......@@ -61,7 +61,7 @@ public class AnalysisContextImpl implements AnalysisContext {
currentReadHolder = readSheetHolder;
selectSheet(excelExecutor);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Began to read:{}", readSheet);
LOGGER.debug("Began to read:{}", readSheetHolder);
}
}
......
......@@ -13,6 +13,7 @@ import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.enums.WriteLastRowType;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.WorkBookUtil;
......@@ -198,6 +199,11 @@ public class WriteContextImpl implements WriteContext {
return;
}
int lastRowNum = writeSheetHolder.getSheet().getLastRowNum();
// 'lastRowNum' doesn't matter if it has one or zero,is's zero
if (lastRowNum == 0 && WriteLastRowType.HAVE_DATA == writeSheetHolder.getWriteLastRowType()) {
lastRowNum = 1;
}
writeSheetHolder.setWriteLastRowType(WriteLastRowType.HAVE_DATA);
int rowIndex = lastRowNum + currentWriteHolder.relativeHeadRowIndex();
// Combined head
addMergedRegionToCurrentSheet(excelWriteHeadProperty, rowIndex);
......
package com.alibaba.excel.enums;
/**
* The types of write last row
*
* @author zhuangjiaju
**/
public enum WriteLastRowType {
/**
* Tables are created without templates ,And any data has been written;
*/
EMPTY,
/**
* It's supposed to have data in it.Tables are created with templates ,or any data has been written;
*/
HAVE_DATA,;
}
......@@ -2,7 +2,7 @@ package com.alibaba.excel.metadata.property;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -113,7 +113,7 @@ public class ExcelHeadProperty {
// When the parent class is null, it indicates that the parent class (Object class) has reached the top
// level.
while (tempClass != null) {
fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));
Collections.addAll(fieldList, tempClass.getDeclaredFields());
// Get the parent class and give it to yourself
tempClass = tempClass.getSuperclass();
}
......@@ -167,7 +167,7 @@ public class ExcelHeadProperty {
if (notForceName) {
tmpHeadList.add(field.getName());
} else {
tmpHeadList = Arrays.asList(excelProperty.value());
Collections.addAll(tmpHeadList, excelProperty.value());
}
Head head = new Head(index, field.getName(), tmpHeadList, forceIndex, !notForceName);
ExcelContentProperty excelContentProperty = new ExcelContentProperty();
......
......@@ -60,25 +60,28 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
getGlobalConfiguration().setUse1904windowing(readBasicParameter.getUse1904windowing());
}
// Initialization property
this.excelReadHeadProperty = new ExcelReadHeadProperty(getClazz(), getHead(), convertAllFiled);
if (readBasicParameter.getHeadRowNumber() == null) {
if (parentAbstractReadHolder == null) {
this.headRowNumber = 1;
if (excelReadHeadProperty.hasHead()) {
this.headRowNumber = excelReadHeadProperty.getHeadRowNumber();
} else {
this.headRowNumber = 1;
}
} else {
this.headRowNumber = parentAbstractReadHolder.getHeadRowNumber();
}
} else {
this.headRowNumber = readBasicParameter.getHeadRowNumber();
}
// Initialization property
this.excelReadHeadProperty = new ExcelReadHeadProperty(getClazz(), getHead(), convertAllFiled);
if (parentAbstractReadHolder == null) {
this.readListenerList = new ArrayList<ReadListener>();
} else {
this.readListenerList = new ArrayList<ReadListener>(parentAbstractReadHolder.getReadListenerList());
}
if (HolderEnum.WORKBOOK.equals(holderType())
&& HeadKindEnum.CLASS.equals(excelReadHeadProperty.getHeadKind())) {
if (HolderEnum.WORKBOOK.equals(holderType())) {
readListenerList.add(new ModelBuildEventListener());
}
if (readBasicParameter.getCustomReadListenerList() != null
......
......@@ -36,7 +36,7 @@ public class ReadSheetHolder extends AbstractReadHolder {
this.readSheet = readSheet;
this.parentReadWorkbookHolder = readWorkbookHolder;
this.sheetNo = readSheet.getSheetNo();
this.sheetName=readSheet.getSheetName();
this.sheetName = readSheet.getSheetName();
}
public ReadSheet getReadSheet() {
......@@ -83,4 +83,9 @@ public class ReadSheetHolder extends AbstractReadHolder {
public HolderEnum holderType() {
return HolderEnum.SHEET;
}
@Override
public String toString() {
return "ReadSheetHolder{" + "sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\'' + "} " + super.toString();
}
}
......@@ -15,6 +15,7 @@ import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.context.WriteContextImpl;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.enums.WriteLastRowType;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.CellData;
......@@ -30,6 +31,7 @@ import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.holder.WriteHolder;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import net.sf.cglib.beans.BeanMap;
......@@ -58,13 +60,21 @@ public class ExcelBuilderImpl implements ExcelBuilder {
if (CollectionUtils.isEmpty(data)) {
return;
}
Sheet currentSheet = context.writeSheetHolder().getSheet();
int rowNum = currentSheet.getLastRowNum();
WriteSheetHolder writeSheetHolder = context.writeSheetHolder();
Sheet currentSheet = writeSheetHolder.getSheet();
int lastRowNum = currentSheet.getLastRowNum();
// 'lastRowNum' doesn't matter if it has one or zero,is's zero
if (lastRowNum == 0 && WriteLastRowType.EMPTY == writeSheetHolder.getWriteLastRowType()) {
lastRowNum--;
}
if (!data.isEmpty()) {
context.writeSheetHolder().setWriteLastRowType(WriteLastRowType.HAVE_DATA);
}
if (context.currentWriteHolder().isNew()) {
rowNum += context.currentWriteHolder().relativeHeadRowIndex();
lastRowNum += context.currentWriteHolder().relativeHeadRowIndex();
}
for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) {
int n = relativeRowIndex + rowNum + 1;
int n = relativeRowIndex + lastRowNum + 1;
addOneRowOfDataToExcel(data.get(relativeRowIndex), n, relativeRowIndex);
}
}
......
......@@ -6,6 +6,7 @@ import java.util.Map;
import org.apache.poi.ss.usermodel.Sheet;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.enums.WriteLastRowType;
import com.alibaba.excel.write.metadata.WriteSheet;
/**
......@@ -39,6 +40,14 @@ public class WriteSheetHolder extends AbstractWriteHolder {
*/
private Map<Integer, WriteTableHolder> hasBeenInitializedTable;
/**
* last column type
*
* @param writeSheet
* @param writeWorkbookHolder
*/
private WriteLastRowType writeLastRowType;
public WriteSheetHolder(WriteSheet writeSheet, WriteWorkbookHolder writeWorkbookHolder) {
super(writeSheet, writeWorkbookHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled());
this.writeSheet = writeSheet;
......@@ -50,6 +59,11 @@ public class WriteSheetHolder extends AbstractWriteHolder {
}
this.parentWriteWorkbookHolder = writeWorkbookHolder;
this.hasBeenInitializedTable = new HashMap<Integer, WriteTableHolder>();
if (writeWorkbookHolder.getTemplateInputStream() == null && writeWorkbookHolder.getTemplateFile() == null) {
writeLastRowType = WriteLastRowType.EMPTY;
} else {
writeLastRowType = WriteLastRowType.HAVE_DATA;
}
}
public WriteSheet getWriteSheet() {
......@@ -100,6 +114,14 @@ public class WriteSheetHolder extends AbstractWriteHolder {
this.hasBeenInitializedTable = hasBeenInitializedTable;
}
public WriteLastRowType getWriteLastRowType() {
return writeLastRowType;
}
public void setWriteLastRowType(WriteLastRowType writeLastRowType) {
this.writeLastRowType = writeLastRowType;
}
@Override
public HolderEnum holderType() {
return HolderEnum.SHEET;
......
......@@ -84,6 +84,7 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty {
if (alreadyRangeSet.contains(i + "-" + j)) {
continue;
}
alreadyRangeSet.add(i + "-" + j);
String headName = headNameList.get(j);
int endX = i;
int endY = j;
......@@ -95,16 +96,12 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty {
break;
}
}
// The current cells are not merged
if (endX == i) {
continue;
}
Set<String> tempAlreadyRangeSet = new HashSet<String>();
outer:
for (int k = j + 1; k < headNameList.size(); k++) {
for (int l = i; l < endX; l++) {
for (int l = i; l <= endX; l++) {
if (headList.get(l).getHeadNameList().get(k).equals(headName)) {
tempAlreadyRangeSet.add(k + "-" + j);
tempAlreadyRangeSet.add(l + "-" + k);
} else {
break outer;
}
......@@ -112,7 +109,7 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty {
endY = k;
alreadyRangeSet.addAll(tempAlreadyRangeSet);
}
cellRangeList.add(new CellRange(i, endY, j, endX));
cellRangeList.add(new CellRange(j, endY, i, endX));
}
}
return cellRangeList;
......
......@@ -12,7 +12,6 @@ import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.DateUtils;
/**
* Annotation data test
*
* @author zhuangjiaju
*/
......
......@@ -16,7 +16,6 @@ import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.util.DateUtils;
/**
* Annotation data test
*
* @author zhuangjiaju
*/
......
package com.alibaba.easyexcel.test.core.head;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class ComplexDataListener extends AnalysisEventListener<ComplexHeadData> {
private static final Logger LOGGER = LoggerFactory.getLogger(ComplexHeadData.class);
List<ComplexHeadData> list = new ArrayList<ComplexHeadData>();
@Override
public void invoke(ComplexHeadData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 1);
ComplexHeadData data = list.get(0);
Assert.assertEquals(data.getString4(), "字符串4");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
package com.alibaba.easyexcel.test.core.head;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class ComplexHeadData {
@ExcelProperty({"顶格", "顶格", "两格"})
private String string0;
@ExcelProperty({"顶格", "顶格", "两格"})
private String string1;
@ExcelProperty({"顶格", "四联", "四联"})
private String string2;
@ExcelProperty({"顶格", "四联", "四联"})
private String string3;
@ExcelProperty({"顶格"})
private String string4;
}
package com.alibaba.easyexcel.test.core.head;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
/**
*
* @author zhuangjiaju
*/
public class ComplexHeadDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("complexHead07.xlsx");
file03 = TestFileUtil.createNewFile("complexHead03.xls");
}
@Test
public void T01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() {
readAndWrite(file03);
}
private void readAndWrite(File file) {
EasyExcelFactory.write(file, ComplexHeadData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, ComplexHeadData.class, new ComplexDataListener()).sheet().doRead().finish();
}
private List<ComplexHeadData> data() {
List<ComplexHeadData> list = new ArrayList<ComplexHeadData>();
ComplexHeadData data = new ComplexHeadData();
data.setString0("字符串0");
data.setString1("字符串1");
data.setString2("字符串2");
data.setString3("字符串3");
data.setString4("字符串4");
list.add(data);
return list;
}
}
package com.alibaba.easyexcel.test.core.head;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class ListHeadDataListener extends AnalysisEventListener<Map<Integer, String>> {
private static final Logger LOGGER = LoggerFactory.getLogger(NoHeadData.class);
List<Map<Integer, String>> list = new ArrayList<Map<Integer, String>>();
@Override
public void invoke(Map<Integer, String> data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 1);
Map<Integer, String> data = list.get(0);
Assert.assertEquals(data.get(0), "字符串0");
Assert.assertEquals(data.get(1), "1.0");
Assert.assertEquals(data.get(2), "2020-01-01 01:01:01");
Assert.assertEquals(data.get(3), "额外数据");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
package com.alibaba.easyexcel.test.core.head;
import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.DateUtils;
/**
*
* @author zhuangjiaju
*/
public class ListHeadDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("listHead07.xlsx");
file03 = TestFileUtil.createNewFile("listHead03.xls");
}
@Test
public void T01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
private void readAndWrite(File file) throws Exception {
EasyExcelFactory.write(file).head(head()).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file).registerReadListener(new ListHeadDataListener()).sheet().doRead().finish();
}
private List<List<String>> head() {
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add("字符串");
List<String> head1 = new ArrayList<String>();
head1.add("数字");
List<String> head2 = new ArrayList<String>();
head2.add("日期");
list.add(head0);
list.add(head1);
list.add(head2);
return list;
}
private List<List<Object>> data() throws ParseException {
List<List<Object>> list = new ArrayList<List<Object>>();
List<Object> data0 = new ArrayList<Object>();
data0.add("字符串0");
data0.add(1);
data0.add(DateUtils.parseDate("2020-01-01 01:01:01"));
data0.add("额外数据");
list.add(data0);
return list;
}
}
package com.alibaba.easyexcel.test.core.head;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class NoHeadData {
@ExcelProperty("字符串")
private String string;
}
package com.alibaba.easyexcel.test.core.head;
import org.junit.Test;
/**
* Order data test
*
* @author zhuangjiaju
*/
public class NoHeadData07Test {
@Test
public void simple() {
// ExcelWriter writer = EasyExcelFactory.writerBuilder().outputFile(TestFileUtil.createNewWriteFile("order07.xlsx"))
// .head(OrderData.class).build();
// Sheet sheet = EasyExcelFactory.writerSheetBuilder().sheetNo(0).sheetName("order").build();
// writer.write(createData(10000 * 100), sheet);
// writer.finish();
}
}
package com.alibaba.easyexcel.test.core.head;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class NoHeadDataListener extends AnalysisEventListener<NoHeadData> {
private static final Logger LOGGER = LoggerFactory.getLogger(NoHeadData.class);
List<NoHeadData> list = new ArrayList<NoHeadData>();
@Override
public void invoke(NoHeadData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 1);
NoHeadData data = list.get(0);
Assert.assertEquals(data.getString(), "字符串0");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}
package com.alibaba.easyexcel.test.core.head;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
/**
*
* @author zhuangjiaju
*/
public class NoHeadDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("noHead07.xlsx");
file03 = TestFileUtil.createNewFile("noHead03.xls");
}
@Test
public void T01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() {
readAndWrite(file03);
}
private void readAndWrite(File file) {
EasyExcelFactory.write(file, NoHeadData.class).needHead(Boolean.FALSE).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, NoHeadData.class, new NoHeadDataListener()).headRowNumber(0).sheet().doRead()
.finish();
}
private List<NoHeadData> data() {
List<NoHeadData> list = new ArrayList<NoHeadData>();
NoHeadData data = new NoHeadData();
data.setString("字符串0");
list.add(data);
return list;
}
}
......@@ -10,8 +10,7 @@ import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
/**
* Large data test
*
*
* @author zhuangjiaju
*/
public class LargeDataTest {
......
......@@ -14,7 +14,6 @@ import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
/**
* Simple data test
*
* @author zhuangjiaju
*/
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册