Pre Merge pull request !354 from panxiaoyang/changeExcelUtil

pull/354/MERGE
panxiaoyang 2 years ago committed by Gitee
commit e6850fd3f8
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F

@ -8,8 +8,10 @@ import java.time.LocalDateTime;
import java.time.LocalTime; import java.time.LocalTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date; import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.StringUtils;
/** /**
* *
@ -127,6 +129,82 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
} }
} }
/**
*
*/
public static LocalDate parseLocalDate(Object str)
{
if (str == null)
{
return null;
}
try
{
return toLocalDate(str.toString(), parsePatterns);
}
catch (ParseException e)
{
return null;
}
}
/**
*
*/
public static LocalDateTime parseLocalDateTime(Object str)
{
if (str == null)
{
return null;
}
try
{
return toLocalDateTime(str.toString(), parsePatterns);
}
catch (ParseException e)
{
return null;
}
}
public static LocalDate toLocalDate(String dateTime, String... formats) throws ParseException{
if (StringUtils.isEmpty(dateTime)) {
return null;
}
if (formats == null || formats.length == 0) {
formats = new String[]{"yyyy-MM-dd"};
}
for(String format:formats){
try
{
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
LocalDate ldt = LocalDate.parse(dateTime, df);
return ldt;
}catch (Exception ignored)
{
}
}
throw new ParseException("转换异常",formats.length);
}
public static LocalDateTime toLocalDateTime(String dateTime, String... formats) throws ParseException{
if (StringUtils.isEmpty(dateTime)) {
return null;
}
if (formats == null || formats.length == 0) {
formats = new String[]{"yyyy-MM-dd HH:mm:ss"};
}
for(String format:formats){
try
{
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
LocalDateTime ldt = LocalDateTime.parse(dateTime, df);
return ldt;
}catch (Exception ignored)
{
}
}
throw new ParseException("转换异常",formats.length);
}
/** /**
* *
*/ */

@ -292,6 +292,21 @@ public class ExcelUtil<T>
return importExcel(StringUtils.EMPTY, is, titleNum); return importExcel(StringUtils.EMPTY, is, titleNum);
} }
/**
* excel
* @return
*/
public Map<String,String> initValueToFieldConversionMap(Excel attr){
HashMap<String, String> conversionMap = new HashMap<>();
String allList = attr.readConverterExp();
String[] split = allList.split(",");
for (String dictTagItem : split)
{
String[] split1 = dictTagItem.split("=");
conversionMap.put(split1[1], split1[0]);
}
return conversionMap;
}
/** /**
* excellist * excellist
* *
@ -336,6 +351,8 @@ public class ExcelUtil<T>
// 有数据时才处理 得到类的所有field. // 有数据时才处理 得到类的所有field.
List<Object[]> fields = this.getFields(); List<Object[]> fields = this.getFields();
Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>(); Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
// 定义所有的excel值和java对象的值的转换映射表
Map<String,Map<String,String>> allFieldConversionMap=new HashMap<>();
for (Object[] objects : fields) for (Object[] objects : fields)
{ {
Excel attr = (Excel) objects[1]; Excel attr = (Excel) objects[1];
@ -343,6 +360,11 @@ public class ExcelUtil<T>
if (column != null) if (column != null)
{ {
fieldsMap.put(column, objects); fieldsMap.put(column, objects);
//如果存在解析键值映射,则直接初始化
if(StringUtils.isNotEmpty(attr.readConverterExp())){
Map<String, String> fieldConversionMap = initValueToFieldConversionMap(attr);
allFieldConversionMap.put(attr.name(),fieldConversionMap);
}
} }
} }
for (int i = titleNum + 1; i <= rows; i++) for (int i = titleNum + 1; i <= rows; i++)
@ -417,6 +439,14 @@ public class ExcelUtil<T>
val = DateUtil.getJavaDate((Double) val); val = DateUtil.getJavaDate((Double) val);
} }
} }
else if (LocalDate.class == fieldType)
{
val = DateUtils.parseLocalDate(val);
}
else if (LocalDateTime.class == fieldType)
{
val = DateUtils.parseLocalDateTime(val);
}
else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
{ {
val = Convert.toBool(val, false); val = Convert.toBool(val, false);
@ -428,9 +458,9 @@ public class ExcelUtil<T>
{ {
propertyName = field.getName() + "." + attr.targetAttr(); propertyName = field.getName() + "." + attr.targetAttr();
} }
if (StringUtils.isNotEmpty(attr.readConverterExp())) if (allFieldConversionMap.get(attr.name())!=null)
{ {
val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); val = getConvertValueByExpMap(Convert.toStr(val), attr.separator(), allFieldConversionMap.get(attr.name()));
} }
else if (!attr.handler().equals(ExcelHandlerAdapter.class)) else if (!attr.handler().equals(ExcelHandlerAdapter.class))
{ {
@ -533,7 +563,8 @@ public class ExcelUtil<T>
for (int index = 0; index < sheetNo; index++) for (int index = 0; index < sheetNo; index++)
{ {
createSheet(sheetNo, index); createSheet(sheetNo, index);
//字段转换列表<列下标,<待转值,转换值>>
Map<Integer, Map<String, String>> fieldConversionMap = new HashMap<>();
// 产生一行 // 产生一行
Row row = sheet.createRow(rownum); Row row = sheet.createRow(rownum);
int column = 0; int column = 0;
@ -547,17 +578,17 @@ public class ExcelUtil<T>
for (Field subField : subFields) for (Field subField : subFields)
{ {
Excel subExcel = subField.getAnnotation(Excel.class); Excel subExcel = subField.getAnnotation(Excel.class);
this.createHeadCell(subExcel, row, column++); this.createHeadCellAndInitFieldConversion(subExcel, row, column++,fieldConversionMap);
} }
} }
else else
{ {
this.createHeadCell(excel, row, column++); this.createHeadCellAndInitFieldConversion(excel, row, column++,fieldConversionMap);
} }
} }
if (Type.EXPORT.equals(type)) if (Type.EXPORT.equals(type))
{ {
fillExcelData(index, row); fillExcelData(index, row, fieldConversionMap);
addStatisticsRow(); addStatisticsRow();
} }
} }
@ -568,9 +599,10 @@ public class ExcelUtil<T>
* *
* @param index * @param index
* @param row * @param row
* @param fieldConversionMap Map
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void fillExcelData(int index, Row row) public void fillExcelData(int index, Row row, Map<Integer, Map<String, String>> fieldConversionMap)
{ {
int startNo = index * sheetSize; int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size()); int endNo = Math.min(startNo + sheetSize, list.size());
@ -618,7 +650,7 @@ public class ExcelUtil<T>
{ {
subField.setAccessible(true); subField.setAccessible(true);
Excel attr = subField.getAnnotation(Excel.class); Excel attr = subField.getAnnotation(Excel.class);
this.addCell(attr, row, (T) obj, subField, column + subIndex); this.addCell(attr, row, (T) obj, subField, column + subIndex, fieldConversionMap);
} }
subIndex++; subIndex++;
} }
@ -628,7 +660,7 @@ public class ExcelUtil<T>
} }
else else
{ {
this.addCell(excel, row, vo, field, column++); this.addCell(excel, row, vo, field, column++, fieldConversionMap);
} }
} }
} }
@ -760,9 +792,9 @@ public class ExcelUtil<T>
} }
/** /**
* * ,
*/ */
public Cell createHeadCell(Excel attr, Row row, int column) public Cell createHeadCellAndInitFieldConversion(Excel attr, Row row, int column, Map<Integer, Map<String, String>> fieldConversionMap)
{ {
// 创建列 // 创建列
Cell cell = row.createCell(column); Cell cell = row.createCell(column);
@ -770,6 +802,19 @@ public class ExcelUtil<T>
cell.setCellValue(attr.name()); cell.setCellValue(attr.name());
setDataValidation(attr, row, column); setDataValidation(attr, row, column);
cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor()))); cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
//字段转换初始化(通过readConverterExp字符转换)
if (StringUtils.isNotEmpty(attr.readConverterExp()))
{
HashMap<String, String> conversionMap = new HashMap<>();
String allList = attr.readConverterExp();
String[] split = allList.split(",");
for (String dictTagItem : split)
{
String[] split1 = dictTagItem.split("=");
conversionMap.put(split1[0], split1[1]);
}
fieldConversionMap.put(column, conversionMap);
}
if (isSubList()) if (isSubList())
{ {
// 填充默认样式,防止合并单元格样式失效 // 填充默认样式,防止合并单元格样式失效
@ -885,8 +930,15 @@ public class ExcelUtil<T>
/** /**
* *
* @param attr
* @param row
* @param vo
* @param field
* @param column
* @param fieldConversionMap
* @return
*/ */
public Cell addCell(Excel attr, Row row, T vo, Field field, int column) public Cell addCell(Excel attr, Row row, T vo, Field field, int column,Map<Integer, Map<String, String>> fieldConversionMap)
{ {
Cell cell = null; Cell cell = null;
try try
@ -908,15 +960,14 @@ public class ExcelUtil<T>
// 用于读取对象中的属性 // 用于读取对象中的属性
Object value = getTargetValue(vo, field, attr); Object value = getTargetValue(vo, field, attr);
String dateFormat = attr.dateFormat(); String dateFormat = attr.dateFormat();
String readConverterExp = attr.readConverterExp();
String separator = attr.separator(); String separator = attr.separator();
if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
{ {
cell.setCellValue(parseDateToStr(dateFormat, value)); cell.setCellValue(parseDateToStr(dateFormat, value));
} }
else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) else if (fieldConversionMap.get(column)!=null && StringUtils.isNotNull(value))
{ {
cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator)); cell.setCellValue(getConvertValueByExpMap(Convert.toStr(value), separator, fieldConversionMap.get(column)));
} }
else if (value instanceof BigDecimal && -1 != attr.scale()) else if (value instanceof BigDecimal && -1 != attr.scale())
{ {
@ -1031,77 +1082,34 @@ public class ExcelUtil<T>
} }
/** /**
* 0=,1=,2= * ,
* *
* @param propertyValue * @param propertyValue
* @param converterExp
* @param separator * @param separator
* @param conversionMap
* @return * @return
*/ */
public static String convertByExp(String propertyValue, String converterExp, String separator) public static String getConvertValueByExpMap(String propertyValue,String separator,Map<String,String> conversionMap){
{ List<String> afterConversionValueList=new ArrayList<>();
StringBuilder propertyString = new StringBuilder(); //如果某个对象值为"1,2,3",则根据转换Map表全都进修转换
String[] convertSource = converterExp.split(",");
for (String item : convertSource)
{
String[] itemArray = item.split("=");
if (StringUtils.containsAny(propertyValue, separator)) if (StringUtils.containsAny(propertyValue, separator))
{ {
for (String value : propertyValue.split(separator)) for (String value : propertyValue.split(separator))
{ {
if (itemArray[0].equals(value)) String conversionValue = conversionMap.get(value);
if(StringUtils.isNotEmpty(conversionValue))
{ {
propertyString.append(itemArray[1] + separator); afterConversionValueList.add(conversionValue);
break;
}
} }
} }
else }else
{ {
if (itemArray[0].equals(propertyValue)) if(StringUtils.isNotEmpty(conversionMap.get(propertyValue)))
{ {
return itemArray[1]; afterConversionValueList.add(conversionMap.get(propertyValue));
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
/**
* =0,=1,=2
*
* @param propertyValue
* @param converterExp
* @param separator
* @return
*/
public static String reverseByExp(String propertyValue, String converterExp, String separator)
{
StringBuilder propertyString = new StringBuilder();
String[] convertSource = converterExp.split(",");
for (String item : convertSource)
{
String[] itemArray = item.split("=");
if (StringUtils.containsAny(propertyValue, separator))
{
for (String value : propertyValue.split(separator))
{
if (itemArray[1].equals(value))
{
propertyString.append(itemArray[0] + separator);
break;
}
}
}
else
{
if (itemArray[1].equals(propertyValue))
{
return itemArray[0];
}
} }
} }
return StringUtils.stripEnd(propertyString.toString(), separator); return String.join(separator,afterConversionValueList);
} }
/** /**

Loading…
Cancel
Save