Excel注解支持多级获取

pull/58/MERGE
RuoYi 2018-12-28 16:15:56 +08:00
parent 63ee2ba2e7
commit 3d3017804d
3 changed files with 64 additions and 4 deletions

View File

@ -63,4 +63,9 @@ public @interface Excel
* ,:,.
*/
public boolean isExport() default true;
/**
* ,,
*/
public String targetAttr() default "";
}

View File

@ -6,6 +6,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@ -344,21 +345,23 @@ public class ExcelUtil<T>
continue;
}
// 用于读取对象中的属性
Object value = getTargetValue(vo, field, attr);
String dateFormat = attr.dateFormat();
String readConverterExp = attr.readConverterExp();
if (StringUtils.isNotEmpty(dateFormat))
{
cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) field.get(vo)));
cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
}
else if (StringUtils.isNotEmpty(readConverterExp))
{
cell.setCellValue(convertByExp(String.valueOf(field.get(vo)), readConverterExp));
cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp));
}
else
{
cell.setCellType(CellType.STRING);
// 如果数据存在就填入,不存在填入空格.
cell.setCellValue(StringUtils.isNull(field.get(vo)) ? attr.defaultValue() : field.get(vo) + attr.suffix());
cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
}
}
}
@ -455,7 +458,7 @@ public class ExcelUtil<T>
sheet.addValidationData(dataValidationList);
return sheet;
}
/**
* 0=,1=,2=
*
@ -509,4 +512,55 @@ public class ExcelUtil<T>
}
return downloadPath;
}
/**
* bean
*
* @param vo
* @param field
* @param excel
* @return
* @throws Exception
*/
private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
{
Object o = field.get(vo);
if (StringUtils.isNotEmpty(excel.targetAttr()))
{
String target = excel.targetAttr();
if (target.indexOf(".") > -1)
{
String[] targets = target.split("[.]");
for (String name : targets)
{
o = getValue(o, name);
}
}
else
{
o = getValue(o, target);
}
}
return o;
}
/**
* get
*
* @param o
* @param name
* @return value
* @throws Exception
*/
private Object getValue(Object o, String name) throws Exception
{
if (StringUtils.isNotEmpty(name))
{
Class<?> clazz = o.getClass();
String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
Method method = clazz.getMethod(methodName);
o = method.invoke(o);
}
return o;
}
}

View File

@ -71,6 +71,7 @@ public class SysUser extends BaseEntity
private Date loginDate;
/** 部门对象 */
@Excel(name = "部门名称", targetAttr = "deptName")
private SysDept dept;
private List<SysRole> roles;