Excel注解支持自定义数据处理器

duhanyu
RuoYi 3 years ago
parent 26f0737c60
commit 3b42abef44

@ -5,6 +5,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;
import com.ruoyi.common.utils.poi.ExcelHandlerAdapter;
/**
* Excel
@ -108,7 +109,17 @@ public @interface Excel
/**
* 0123
*/
Align align() default Align.AUTO;
public Align align() default Align.AUTO;
/**
*
*/
public Class<?> handler() default ExcelHandlerAdapter.class;
/**
*
*/
public String[] args() default {};
public enum Align
{

@ -0,0 +1,19 @@
package com.ruoyi.common.utils.poi;
/**
* Excel
*
* @author ruoyi
*/
public interface ExcelHandlerAdapter
{
/**
*
*
* @param value
* @param args excelargs
*
* @return
*/
Object format(Object value, String[] args);
}

@ -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.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
@ -333,6 +334,10 @@ public class ExcelUtil<T>
{
val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
}
else if (!attr.handler().equals(ExcelHandlerAdapter.class))
{
val = dataFormatHandlerAdapter(val, attr);
}
else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
{
PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
@ -729,6 +734,10 @@ public class ExcelUtil<T>
{
cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
}
else if (!attr.handler().equals(ExcelHandlerAdapter.class))
{
cell.setCellValue(dataFormatHandlerAdapter(value, attr));
}
else
{
// 设置列类型
@ -901,6 +910,28 @@ public class ExcelUtil<T>
return DictUtils.getDictValue(dictType, dictLabel, separator);
}
/**
*
*
* @param value
* @param excel
* @return
*/
public String dataFormatHandlerAdapter(Object value, Excel excel)
{
try
{
Object instance = excel.handler().newInstance();
Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class });
value = formatMethod.invoke(instance, value, excel.args());
}
catch (Exception e)
{
log.error("不能格式化数据 " + excel.handler(), e.getMessage());
}
return Convert.toStr(value);
}
/**
*
*/

Loading…
Cancel
Save