Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@
</profiles>

<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
Expand Down
162 changes: 113 additions & 49 deletions src/main/java/net/fenghaitao/AutoExcel.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import net.fenghaitao.utils.SheetUtil;
import net.fenghaitao.export.managers.*;
import net.fenghaitao.parameters.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
Expand All @@ -25,6 +26,8 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static net.fenghaitao.utils.ClassUtil.mapFieldNameField;

public class AutoExcel {
private static final String regCellName = "'?%s'?!\\$([a-z]+)\\$([0-9]+)";
private static final Pattern cellRefPattern = Pattern.compile("([a-z]+)([0-9]+)", Pattern.CASE_INSENSITIVE);
Expand Down Expand Up @@ -193,57 +196,104 @@ public static void save(String outputPath, DirectExportPara directExportPara) {
*/
public static void save(String outputPath, List<DirectExportPara> directExportParas) {
ExportContext exportContext = new ExportContext(ExportType.Direct);
// Workbook workbook = exportContext.getWorkbook();

for (DirectExportPara directExportPara : directExportParas) {
createSheet(exportContext,directExportPara);
}
exportContext.end(outputPath);
}

//如果具体数据为list,title与数据填充都完全不一样,需要拆开

public static void createSheet(ExportContext exportContext,DirectExportPara directExportPara) {
Workbook workbook = exportContext.getWorkbook();
Sheet sheet;
if (directExportPara.getDataSource() == null)
return;

for (DirectExportPara directExportPara : directExportParas) {
if (directExportPara.getDataSource() == null)
continue;
if (StringUtils.isEmpty(directExportPara.getSheetName()))
sheet = workbook.createSheet();
else
sheet = workbook.createSheet(directExportPara.getSheetName());

if (directExportPara.getSheetName() == null || directExportPara.getSheetName().isEmpty())
sheet = workbook.createSheet();
else
sheet = workbook.createSheet(directExportPara.getSheetName());
if (List.class.isAssignableFrom(directExportPara.getObjectType())) {
createListSheet(directExportPara,sheet,exportContext);
} else {
createProjectSheet(directExportPara, sheet, exportContext);
}

DataSourceType dataSourceType = directExportPara.getDataSourceType();
Map<String, Field> fieldNameFields = mapFieldNameField(directExportPara.getObjectType());
SheetUtil.setColumnWidth(sheet, 0, directExportPara.getFieldSettings().size(), exportContext);

List<FieldSetting> fieldSettings = directExportPara.getFieldSettings();
if (fieldSettings == null || fieldSettings.size() == 0) {
fieldSettings = fieldNameFields.values()
.stream()
.map(m -> new FieldSetting(m.getName(), m.getName()))
.collect(Collectors.toList());
}
int rowIndex = 0;
int colIndex = 0;
//write title
for (FieldSetting fieldSetting : fieldSettings) {
SheetUtil.setValue(sheet, rowIndex, colIndex, fieldSetting.getDisplayName(), exportContext)
.setCellStyle(exportContext.getDefaultHeadStyle());
exportContext.refreshMaxColumnWidth(sheet.getSheetName(), colIndex, fieldSetting.getDisplayName());
++colIndex;
}
//write data
++rowIndex;
try {
if (dataSourceType == DataSourceType.List) {
for (Object record : (List) directExportPara.getDataSource()) {
writeRecordByFieldSetting(sheet, fieldSettings, record, fieldNameFields,
}

public static void createProjectSheet(DirectExportPara directExportPara,Sheet sheet,
ExportContext exportContext) {
Map<String, Field> fieldNameFields = mapFieldNameField(directExportPara.getObjectType());
List<FieldSetting> fieldSettings = directExportPara.getFieldSettings();
DataSourceType dataSourceType = directExportPara.getDataSourceType();


int rowIndex = 0;
int colIndex = 0;
//write title
for (FieldSetting fieldSetting : fieldSettings) {
SheetUtil.setValue(sheet, rowIndex, colIndex, fieldSetting.getDisplayName(), exportContext)
.setCellStyle(exportContext.getDefaultHeadStyle());
exportContext.refreshMaxColumnWidth(sheet.getSheetName(), colIndex, fieldSetting.getDisplayName());
++colIndex;
}
//write data
++rowIndex;
try {
if (dataSourceType == DataSourceType.List) {
for (Object record : (List) directExportPara.getDataSource()) {
writeRecordByFieldSetting(sheet, fieldSettings, record,fieldNameFields,
rowIndex, exportContext);
++rowIndex;
}
} else {
writeRecordByFieldSetting(sheet, fieldSettings, directExportPara.getDataSource(),
fieldNameFields, rowIndex, exportContext);
++rowIndex;
}
} else {
writeRecordByFieldSetting(sheet, fieldSettings, directExportPara.getDataSource(),
fieldNameFields, rowIndex, exportContext);
}
catch (IllegalAccessException e) {
throw new AutoExcelException(e);
} catch (IllegalAccessException e) {
throw new AutoExcelException(e);
}
}

public static void createListSheet(DirectExportPara directExportPara,Sheet sheet,ExportContext exportContext) {
List<FieldSetting> fieldSettings = directExportPara.getFieldSettings();
DataSourceType dataSourceType = directExportPara.getDataSourceType();

//auto generate filedSettings,use filed name as display name
if (fieldSettings == null || fieldSettings.size() == 0) {
throw new AutoExcelException("List title is null");
}
int rowIndex = 0;
int colIndex = 0;
//write title
for (FieldSetting fieldSetting : fieldSettings) {
SheetUtil.setValue(sheet, rowIndex, colIndex, fieldSetting.getDisplayName(), exportContext)
.setCellStyle(exportContext.getDefaultHeadStyle());
exportContext.refreshMaxColumnWidth(sheet.getSheetName(), colIndex, fieldSetting.getDisplayName());
++colIndex;
}
//write data
++rowIndex;
try {
if (dataSourceType == DataSourceType.List) {
for (Object record : (List) directExportPara.getDataSource()) {
writeRecordByFieldSetting(sheet, fieldSettings, record, rowIndex, exportContext);
++rowIndex;
}
} else {
writeRecordByFieldSetting(sheet, fieldSettings, directExportPara.getDataSource(),
rowIndex, exportContext);
}
SheetUtil.setColumnWidth(sheet, 0, fieldSettings.size(), exportContext);
}
exportContext.end(outputPath);
catch (IllegalAccessException e) {
throw new AutoExcelException(e);
}
}

/**
Expand Down Expand Up @@ -362,16 +412,7 @@ private static List<BlockNameResolver> resolveCellNames(Workbook workbook,
return blockNameResolvers;
}

/**
* Generate filedName-properties key value mapping
*/
private static Map<String, Field> mapFieldNameField(Class aClass) {
Map<String, Field> result = new HashMap<>(16);
for (Field field : aClass.getDeclaredFields())
result.put(field.getName().toLowerCase(), field);

return result;
}

/**
* ReLocate the cell. After the row is moved, the original cell position changes and the cell location saved in the
Expand Down Expand Up @@ -469,6 +510,29 @@ private static void writeRecordByFieldSetting(Sheet sheet,
}
}

/**
* Write a record to sheet according to the fieldSettings
*/
private static void writeRecordByFieldSetting(Sheet sheet,
List<FieldSetting> fieldSettings,
Object dataSourceRecord,
int rowIndex,
ExportContext exportContext) throws IllegalAccessException {
int colIndex = 0;
List listData = (List) dataSourceRecord;
for (int i = 0; i < fieldSettings.size(); i++) {
Object value = listData.get(i);
Cell cell = SheetUtil.setValue(sheet, rowIndex, colIndex, value, exportContext);
CellUtil.setStyle(cell, value, exportContext);
exportContext.refreshMaxColumnWidth(sheet.getSheetName(), colIndex, value);
colIndex++;
}
}





/**
* Assign value to the aggregate cells
*/
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/net/fenghaitao/context/ExportContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,7 @@ public void refreshMaxColumnWidth(String sheetName, int colIndex, Object value)
if (columnWidthMap == null) {
columnWidthMap = new HashMap<>(16);
sheetColumnWidthMap.put(sheetName, columnWidthMap);
}
else {
} else {
curColWidth = columnWidthMap.get(colIndex);
}

Expand Down
18 changes: 15 additions & 3 deletions src/main/java/net/fenghaitao/parameters/DirectExportPara.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package net.fenghaitao.parameters;

import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

import static net.fenghaitao.utils.ClassUtil.mapFieldNameField;

/**
* The parameter for exporting directly
Expand All @@ -16,17 +20,25 @@ public class DirectExportPara extends ExportPara {
private List<FieldSetting> fieldSettings;

public DirectExportPara(Object dataSource) {
super.setDataSource(dataSource);
this(dataSource,null);
}

public DirectExportPara(Object dataSource, List<FieldSetting> fieldSettings) {
super.setDataSource(dataSource);
this.fieldSettings = fieldSettings;
this(dataSource,null,fieldSettings);

}

public DirectExportPara(Object dataSource, String sheetName, List<FieldSetting> fieldSettings) {
super.setDataSource(dataSource);
this.sheetName = sheetName;

//auto generate filedSettings,use filed name as display name
if (CollectionUtils.isEmpty(fieldSettings)) {
fieldSettings = mapFieldNameField(this.getObjectType()).values()
.stream()
.map(m -> new FieldSetting(m.getName(), m.getName()))
.collect(Collectors.toList());
}
this.fieldSettings = fieldSettings;
}
}
Expand Down
18 changes: 18 additions & 0 deletions src/main/java/net/fenghaitao/utils/ClassUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package net.fenghaitao.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ClassUtil {
/**
* Generate filedName-properties key value mapping
*/
public static Map<String, Field> mapFieldNameField(Class aClass) {
Map<String, Field> result = new HashMap<>(16);
for (Field field : aClass.getDeclaredFields())
result.put(field.getName().toLowerCase(), field);

return result;
}
}
4 changes: 3 additions & 1 deletion src/test/java/net/fenghaitao/AutoExcelTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ public void exportDirectly() throws ParseException {
List<DirectExportPara> paras = new ArrayList<>();
paras.add(new DirectExportPara(DataGenerator.genProjects(200), "Projects",
DataGenerator.genProjectFieldSettings()));
paras.add(new DirectExportPara(DataGenerator.genContracts()));
paras.add(new DirectExportPara(DataGenerator.genSingleContracts()));
paras.add(new DirectExportPara(DataGenerator.genListPorjects(10),"lists",
DataGenerator.genListFieldSettings()));
AutoExcel.save(outputPath, paras);
}

Expand Down
31 changes: 27 additions & 4 deletions src/test/java/net/fenghaitao/DataGenerator.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package net.fenghaitao;

import java.util.Date;
import java.util.*;

import net.fenghaitao.model.BusinessUnit;
import net.fenghaitao.model.Contract;
import net.fenghaitao.model.Product;
Expand All @@ -11,8 +12,6 @@
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class DataGenerator {

Expand All @@ -34,7 +33,31 @@ public static List<Contract> genContracts() throws ParseException {
return contracts;
}

public static List<Project> genProjects(int times) throws ParseException {
public static Contract genSingleContracts() throws ParseException {
return new Contract("C0000-0005", "Expected contract", format.parse("2020-07-15 18:10"), new BigDecimal("28500.00"), new BigDecimal("0"), new BigDecimal("0"));
}


public static List<Object> genListPorjects(int times) {
List<Object> listProjects = new ArrayList<>();
ArrayList<String> strings = new ArrayList<>();
Collections.addAll(strings,"Project Name 01", "Some text here. Some text here. 1", "test1");
for (int i = 0; i < times; i++) {
Collections.addAll(listProjects,strings,strings,strings);
}
return listProjects;
}

public static List<FieldSetting> genListFieldSettings() {
List<FieldSetting> fieldSettings = new ArrayList<>();
fieldSettings.add(new FieldSetting("projName", "Project Name"));
fieldSettings.add(new FieldSetting("projInfo", "Project Info."));
fieldSettings.add(new FieldSetting("basalArea", "Basal Area"));
return fieldSettings;
}


public static List<Project> genProjects(int times) throws ParseException {
List<Project> projects = new ArrayList<>();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < times; ++i) {
Expand Down