@@ -129,4 +129,12 @@ public @interface Excel { | |||||
* @return | * @return | ||||
*/ | */ | ||||
public boolean isHyperlink() default false; | public boolean isHyperlink() default false; | ||||
/** | |||||
* 导入时会校验这个字段,看看这个字段是不是导入的Excel中有,如果没有说明是错误的Excel | |||||
* 本意是想用true的,想想还是false比较好 | |||||
* 可以使用a_id,b_id来确实是否使用 | |||||
* @return | |||||
*/ | |||||
public String isImportField() default "false"; | |||||
} | } |
@@ -17,15 +17,16 @@ package org.jeecgframework.poi.excel; | |||||
import java.io.File; | import java.io.File; | ||||
import java.io.FileInputStream; | import java.io.FileInputStream; | ||||
import java.io.IOException; | |||||
import java.io.InputStream; | import java.io.InputStream; | ||||
import java.util.List; | import java.util.List; | ||||
import org.apache.poi.util.IOUtils; | |||||
import org.jeecgframework.poi.excel.entity.ImportParams; | import org.jeecgframework.poi.excel.entity.ImportParams; | ||||
import org.jeecgframework.poi.excel.entity.result.ExcelImportResult; | import org.jeecgframework.poi.excel.entity.result.ExcelImportResult; | ||||
import org.jeecgframework.poi.excel.imports.ExcelImportServer; | import org.jeecgframework.poi.excel.imports.ExcelImportServer; | ||||
import org.jeecgframework.poi.excel.imports.sax.SaxReadExcel; | import org.jeecgframework.poi.excel.imports.sax.SaxReadExcel; | ||||
import org.jeecgframework.poi.excel.imports.sax.parse.ISaxRowRead; | import org.jeecgframework.poi.excel.imports.sax.parse.ISaxRowRead; | ||||
import org.jeecgframework.poi.exception.excel.ExcelImportException; | |||||
import org.jeecgframework.poi.handler.inter.IExcelReadRowHanlder; | import org.jeecgframework.poi.handler.inter.IExcelReadRowHanlder; | ||||
import org.slf4j.Logger; | import org.slf4j.Logger; | ||||
import org.slf4j.LoggerFactory; | import org.slf4j.LoggerFactory; | ||||
@@ -56,20 +57,17 @@ public class ExcelImportUtil { | |||||
*/ | */ | ||||
public static <T> List<T> importExcel(File file, Class<?> pojoClass, ImportParams params) { | public static <T> List<T> importExcel(File file, Class<?> pojoClass, ImportParams params) { | ||||
FileInputStream in = null; | FileInputStream in = null; | ||||
List<T> result = null; | |||||
try { | try { | ||||
in = new FileInputStream(file); | in = new FileInputStream(file); | ||||
result = new ExcelImportServer().importExcelByIs(in, pojoClass, params).getList(); | |||||
return new ExcelImportServer().importExcelByIs(in, pojoClass, params).getList(); | |||||
} catch (ExcelImportException e) { | |||||
throw new ExcelImportException(e.getType(), e); | |||||
} catch (Exception e) { | } catch (Exception e) { | ||||
LOGGER.error(e.getMessage(), e); | LOGGER.error(e.getMessage(), e); | ||||
throw new ExcelImportException(e.getMessage(), e); | |||||
} finally { | } finally { | ||||
try { | |||||
in.close(); | |||||
} catch (IOException e) { | |||||
LOGGER.error(e.getMessage(), e); | |||||
} | |||||
IOUtils.closeQuietly(in); | |||||
} | } | ||||
return result; | |||||
} | } | ||||
/** | /** | ||||
@@ -116,16 +114,14 @@ public class ExcelImportUtil { | |||||
try { | try { | ||||
in = new FileInputStream(file); | in = new FileInputStream(file); | ||||
return new ExcelImportServer().importExcelByIs(in, pojoClass, params); | return new ExcelImportServer().importExcelByIs(in, pojoClass, params); | ||||
} catch (ExcelImportException e) { | |||||
throw new ExcelImportException(e.getType(), e); | |||||
} catch (Exception e) { | } catch (Exception e) { | ||||
LOGGER.error(e.getMessage(), e); | LOGGER.error(e.getMessage(), e); | ||||
throw new ExcelImportException(e.getMessage(), e); | |||||
} finally { | } finally { | ||||
try { | |||||
in.close(); | |||||
} catch (IOException e) { | |||||
LOGGER.error(e.getMessage(), e); | |||||
} | |||||
IOUtils.closeQuietly(in); | |||||
} | } | ||||
return null; | |||||
} | } | ||||
/** | /** | ||||
@@ -71,6 +71,10 @@ public class ImportParams extends ExcelBaseParams { | |||||
* 最后的无效行数 | * 最后的无效行数 | ||||
*/ | */ | ||||
private int lastOfInvalidRow = 0; | private int lastOfInvalidRow = 0; | ||||
/** | |||||
* 导入时校验数据模板,是不是正确的Excel | |||||
*/ | |||||
private String[] importFields; | |||||
public int getHeadRows() { | public int getHeadRows() { | ||||
return headRows; | return headRows; | ||||
@@ -160,4 +164,12 @@ public class ImportParams extends ExcelBaseParams { | |||||
this.needVerfiy = needVerfiy; | this.needVerfiy = needVerfiy; | ||||
} | } | ||||
public String[] getImportFields() { | |||||
return importFields; | |||||
} | |||||
public void setImportFields(String[] importFields) { | |||||
this.importFields = importFields; | |||||
} | |||||
} | } |
@@ -43,6 +43,10 @@ public class ExcelImportEntity extends ExcelBaseEntity { | |||||
* 后缀 | * 后缀 | ||||
*/ | */ | ||||
private String suffix; | private String suffix; | ||||
/** | |||||
* 导入校验字段 | |||||
*/ | |||||
private boolean importField; | |||||
private List<ExcelImportEntity> list; | private List<ExcelImportEntity> list; | ||||
@@ -94,4 +98,12 @@ public class ExcelImportEntity extends ExcelBaseEntity { | |||||
this.suffix = suffix; | this.suffix = suffix; | ||||
} | } | ||||
public boolean isImportField() { | |||||
return importField; | |||||
} | |||||
public void setImportField(boolean importField) { | |||||
this.importField = importField; | |||||
} | |||||
} | } |
@@ -57,6 +57,7 @@ import org.slf4j.LoggerFactory; | |||||
* @author JueYue | * @author JueYue | ||||
* @date 2014年6月17日 下午6:15:13 | * @date 2014年6月17日 下午6:15:13 | ||||
*/ | */ | ||||
@SuppressWarnings("unchecked") | |||||
public abstract class ExcelExportBase extends ExportBase { | public abstract class ExcelExportBase extends ExportBase { | ||||
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExportBase.class); | private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExportBase.class); | ||||
@@ -44,6 +44,7 @@ import org.jeecgframework.poi.util.PoiReflectorUtil; | |||||
* @author JueYue | * @author JueYue | ||||
* @date 2014年8月9日 下午11:01:32 | * @date 2014年8月9日 下午11:01:32 | ||||
*/ | */ | ||||
@SuppressWarnings("rawtypes") | |||||
public class ExportBase { | public class ExportBase { | ||||
protected IExcelDataHandler dataHanlder; | protected IExcelDataHandler dataHanlder; | ||||
@@ -123,8 +124,8 @@ public class ExportBase { | |||||
getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() | getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() | ||||
: targetId, PoiPublicUtil.getClassFields(clz), list, clz, null); | : targetId, PoiPublicUtil.getClassFields(clz), list, clz, null); | ||||
excelEntity = new ExcelExportEntity(); | excelEntity = new ExcelExportEntity(); | ||||
excelEntity.setName(getExcelName(excel.name(), targetId)); | |||||
excelEntity.setOrderNum(getCellOrder(excel.orderNum(), targetId)); | |||||
excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId,null)); | |||||
excelEntity.setOrderNum(Integer.valueOf(PoiPublicUtil.getValueByTargetId(excel.orderNum(), targetId,"0"))); | |||||
excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); | excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); | ||||
excelEntity.setList(list); | excelEntity.setList(list); | ||||
excelParams.add(excelEntity); | excelParams.add(excelEntity); | ||||
@@ -142,28 +143,6 @@ public class ExportBase { | |||||
} | } | ||||
} | } | ||||
/** | |||||
* 获取这个字段的顺序 | |||||
* | |||||
* @param orderNum | |||||
* @param targetId | |||||
* @return | |||||
*/ | |||||
public int getCellOrder(String orderNum, String targetId) { | |||||
if (isInteger(orderNum) || targetId == null) { | |||||
return Integer.valueOf(orderNum); | |||||
} | |||||
String[] arr = orderNum.split(","); | |||||
String[] temp; | |||||
for (String str : arr) { | |||||
temp = str.split("_"); | |||||
if (targetId.equals(temp[1])) { | |||||
return Integer.valueOf(temp[0]); | |||||
} | |||||
} | |||||
return 0; | |||||
} | |||||
/** | /** | ||||
* 获取填如这个cell的值,提供一些附加功能 | * 获取填如这个cell的值,提供一些附加功能 | ||||
* | * | ||||
@@ -172,6 +151,7 @@ public class ExportBase { | |||||
* @return | * @return | ||||
* @throws Exception | * @throws Exception | ||||
*/ | */ | ||||
@SuppressWarnings("unchecked") | |||||
public Object getCellValue(ExcelExportEntity entity, Object obj) throws Exception { | public Object getCellValue(ExcelExportEntity entity, Object obj) throws Exception { | ||||
Object value; | Object value; | ||||
if (obj instanceof Map) { | if (obj instanceof Map) { | ||||
@@ -224,14 +204,14 @@ public class ExportBase { | |||||
*/ | */ | ||||
private void getExcelField(String targetId, Field field, ExcelExportEntity excelEntity, | private void getExcelField(String targetId, Field field, ExcelExportEntity excelEntity, | ||||
Excel excel, Class<?> pojoClass) throws Exception { | Excel excel, Class<?> pojoClass) throws Exception { | ||||
excelEntity.setName(getExcelName(excel.name(), targetId)); | |||||
excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId, null)); | |||||
excelEntity.setWidth(excel.width()); | excelEntity.setWidth(excel.width()); | ||||
excelEntity.setHeight(excel.height()); | excelEntity.setHeight(excel.height()); | ||||
excelEntity.setNeedMerge(excel.needMerge()); | excelEntity.setNeedMerge(excel.needMerge()); | ||||
excelEntity.setMergeVertical(excel.mergeVertical()); | excelEntity.setMergeVertical(excel.mergeVertical()); | ||||
excelEntity.setMergeRely(excel.mergeRely()); | excelEntity.setMergeRely(excel.mergeRely()); | ||||
excelEntity.setReplace(excel.replace()); | excelEntity.setReplace(excel.replace()); | ||||
excelEntity.setOrderNum(getCellOrder(excel.orderNum(), targetId)); | |||||
excelEntity.setOrderNum(Integer.valueOf(PoiPublicUtil.getValueByTargetId(excel.orderNum(), targetId, "0"))); | |||||
excelEntity.setWrap(excel.isWrap()); | excelEntity.setWrap(excel.isWrap()); | ||||
excelEntity.setExportImageType(excel.imageType()); | excelEntity.setExportImageType(excel.imageType()); | ||||
excelEntity.setSuffix(excel.suffix()); | excelEntity.setSuffix(excel.suffix()); | ||||
@@ -243,25 +223,6 @@ public class ExportBase { | |||||
excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); | excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); | ||||
} | } | ||||
/** | |||||
* 判断在这个单元格显示的名称 | |||||
* | |||||
* @param exportName | |||||
* @param targetId | |||||
* @return | |||||
*/ | |||||
public String getExcelName(String exportName, String targetId) { | |||||
if (exportName.indexOf(",") < 0) { | |||||
return exportName; | |||||
} | |||||
String[] arr = exportName.split(","); | |||||
for (String str : arr) { | |||||
if (str.indexOf(targetId) != -1) { | |||||
return str.split("_")[0]; | |||||
} | |||||
} | |||||
return null; | |||||
} | |||||
/** | /** | ||||
* 多个反射获取值 | * 多个反射获取值 | ||||
@@ -522,9 +522,9 @@ public final class ExcelExportOfTemplateUtil extends ExcelExportBase { | |||||
while (true) { | while (true) { | ||||
int colSpan = columns.get(columns.size() - 1) != null | int colSpan = columns.get(columns.size() - 1) != null | ||||
? columns.get(columns.size() - 1).getColspan() : 1; | ? columns.get(columns.size() - 1).getColspan() : 1; | ||||
index += columns.get(columns.size() - 1).getColspan(); | |||||
index += colSpan; | |||||
for (int i = 1; i < colSpan; i++) { | for (int i = 1; i < colSpan; i++) { | ||||
//添加跳过的数据 | |||||
//添加合并的单元格,这些单元可能不是空,但是没有值,所以也需要跳过 | |||||
columns.add(null); | columns.add(null); | ||||
continue; | continue; | ||||
} | } | ||||
@@ -242,7 +242,8 @@ public class CellValueServer { | |||||
*/ | */ | ||||
private Object getValueByType(String xclass, Object result, ExcelImportEntity entity) { | private Object getValueByType(String xclass, Object result, ExcelImportEntity entity) { | ||||
try { | try { | ||||
if(result == null){ | |||||
//过滤空和空字符串,如果基本类型null会在上层抛出,这里就不处理了 | |||||
if(result == null || StringUtils.isBlank(result.toString())){ | |||||
return null; | return null; | ||||
} | } | ||||
if ("class java.util.Date".equals(xclass)) { | if ("class java.util.Date".equals(xclass)) { | ||||
@@ -27,12 +27,6 @@ import java.util.HashMap; | |||||
import java.util.Iterator; | import java.util.Iterator; | ||||
import java.util.List; | import java.util.List; | ||||
import java.util.Map; | import java.util.Map; | ||||
import java.util.Set; | |||||
import javax.validation.ConstraintViolation; | |||||
import javax.validation.Validation; | |||||
import javax.validation.Validator; | |||||
import javax.validation.ValidatorFactory; | |||||
import org.apache.commons.lang3.StringUtils; | import org.apache.commons.lang3.StringUtils; | ||||
import org.apache.poi.POIXMLDocument; | import org.apache.poi.POIXMLDocument; | ||||
@@ -62,6 +56,7 @@ import org.jeecgframework.poi.exception.excel.enums.ExcelImportEnum; | |||||
import org.jeecgframework.poi.handler.inter.IExcelModel; | import org.jeecgframework.poi.handler.inter.IExcelModel; | ||||
import org.jeecgframework.poi.util.PoiPublicUtil; | import org.jeecgframework.poi.util.PoiPublicUtil; | ||||
import org.jeecgframework.poi.util.PoiReflectorUtil; | import org.jeecgframework.poi.util.PoiReflectorUtil; | ||||
import org.jeecgframework.poi.util.PoiValidationUtil; | |||||
import org.slf4j.Logger; | import org.slf4j.Logger; | ||||
import org.slf4j.LoggerFactory; | import org.slf4j.LoggerFactory; | ||||
@@ -76,13 +71,6 @@ public class ExcelImportServer extends ImportBaseService { | |||||
private final static Logger LOGGER = LoggerFactory.getLogger(ExcelImportServer.class); | private final static Logger LOGGER = LoggerFactory.getLogger(ExcelImportServer.class); | ||||
private final static Validator validator; | |||||
static { | |||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); | |||||
validator = factory.getValidator(); | |||||
} | |||||
private CellValueServer cellValueServer; | private CellValueServer cellValueServer; | ||||
private boolean verfiyFail = false; | private boolean verfiyFail = false; | ||||
@@ -207,6 +195,7 @@ public class ExcelImportServer extends ImportBaseService { | |||||
rows.next(); | rows.next(); | ||||
} | } | ||||
Map<Integer, String> titlemap = getTitleMap(rows, params, excelCollection); | Map<Integer, String> titlemap = getTitleMap(rows, params, excelCollection); | ||||
checkIsValidTemplate(titlemap, excelParams, params,excelCollection); | |||||
Row row = null; | Row row = null; | ||||
Object object = null; | Object object = null; | ||||
String picId; | String picId; | ||||
@@ -270,14 +259,13 @@ public class ExcelImportServer extends ImportBaseService { | |||||
boolean isAdd = true; | boolean isAdd = true; | ||||
Cell cell = null; | Cell cell = null; | ||||
if (params.isNeedVerfiy()) { | if (params.isNeedVerfiy()) { | ||||
Set<ConstraintViolation<Object>> set = validator.validate(object); | |||||
if (set.size() > 0) { | |||||
String errorMsg = PoiValidationUtil.validation(object); | |||||
if (StringUtils.isNotEmpty(errorMsg)) { | |||||
cell = row.createCell(row.getLastCellNum()); | cell = row.createCell(row.getLastCellNum()); | ||||
String errMsg = getValidateErrMsg(set); | |||||
cell.setCellValue(errMsg); | |||||
cell.setCellValue(errorMsg); | |||||
if (object instanceof IExcelModel) { | if (object instanceof IExcelModel) { | ||||
IExcelModel model = (IExcelModel) object; | IExcelModel model = (IExcelModel) object; | ||||
model.setErrorMsg(errMsg); | |||||
model.setErrorMsg(errorMsg); | |||||
} else { | } else { | ||||
isAdd = false; | isAdd = false; | ||||
} | } | ||||
@@ -304,14 +292,6 @@ public class ExcelImportServer extends ImportBaseService { | |||||
return isAdd; | return isAdd; | ||||
} | } | ||||
private String getValidateErrMsg(Set<ConstraintViolation<Object>> set) { | |||||
StringBuilder builder = new StringBuilder(); | |||||
for (ConstraintViolation<Object> constraintViolation : set) { | |||||
builder.append(constraintViolation.getMessage()).append(","); | |||||
} | |||||
return builder.substring(0, builder.length() - 1).toString(); | |||||
} | |||||
/** | /** | ||||
* 获取表格字段列名对应信息 | * 获取表格字段列名对应信息 | ||||
* @param rows | * @param rows | ||||
@@ -428,6 +408,41 @@ public class ExcelImportServer extends ImportBaseService { | |||||
return new ExcelImportResult(result, verfiyFail, book); | return new ExcelImportResult(result, verfiyFail, book); | ||||
} | } | ||||
/** | |||||
* 检查是不是合法的模板 | |||||
* @param titlemap | |||||
* @param excelParams | |||||
* @param params | |||||
* @param excelCollection | |||||
*/ | |||||
private void checkIsValidTemplate(Map<Integer, String> titlemap, Map<String, ExcelImportEntity> excelParams, ImportParams params, List<ExcelCollectionParams> excelCollection) { | |||||
if(params.getImportFields() != null){ | |||||
for (int i = 0 ,le = params.getImportFields().length; i < le; i++) { | |||||
if(!titlemap.containsValue(params.getImportFields()[i])){ | |||||
throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); | |||||
} | |||||
} | |||||
} else { | |||||
Collection<ExcelImportEntity> collection = excelParams.values(); | |||||
for (ExcelImportEntity excelImportEntity : collection) { | |||||
if(excelImportEntity.isImportField() && !titlemap.containsValue(excelImportEntity.getName())){ | |||||
throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); | |||||
} | |||||
} | |||||
for (int i = 0, le = excelCollection.size(); i < le; i++) { | |||||
ExcelCollectionParams collectionparams = excelCollection.get(i); | |||||
collection = collectionparams.getExcelParams().values(); | |||||
for (ExcelImportEntity excelImportEntity : collection) { | |||||
if(excelImportEntity.isImportField() && !titlemap.containsValue(collectionparams.getExcelName()+"_"+excelImportEntity.getName())){ | |||||
throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); | |||||
} | |||||
} | |||||
} | |||||
} | |||||
} | |||||
/** | /** | ||||
* 保存字段值(获取值,校验值,追加错误信息) | * 保存字段值(获取值,校验值,追加错误信息) | ||||
* | * | ||||
@@ -34,6 +34,7 @@ import org.apache.poi.ss.usermodel.Workbook; | |||||
import org.apache.poi.util.IOUtils; | import org.apache.poi.util.IOUtils; | ||||
import org.jeecgframework.poi.excel.annotation.Excel; | import org.jeecgframework.poi.excel.annotation.Excel; | ||||
import org.jeecgframework.poi.excel.annotation.ExcelCollection; | import org.jeecgframework.poi.excel.annotation.ExcelCollection; | ||||
import org.jeecgframework.poi.excel.annotation.ExcelEntity; | |||||
import org.jeecgframework.poi.excel.entity.ImportParams; | import org.jeecgframework.poi.excel.entity.ImportParams; | ||||
import org.jeecgframework.poi.excel.entity.params.ExcelCollectionParams; | import org.jeecgframework.poi.excel.entity.params.ExcelCollectionParams; | ||||
import org.jeecgframework.poi.excel.entity.params.ExcelImportEntity; | import org.jeecgframework.poi.excel.entity.params.ExcelImportEntity; | ||||
@@ -69,6 +70,8 @@ public class ImportBaseService { | |||||
excelEntity.setReplace(excel.replace()); | excelEntity.setReplace(excel.replace()); | ||||
excelEntity.setDatabaseFormat(excel.databaseFormat()); | excelEntity.setDatabaseFormat(excel.databaseFormat()); | ||||
excelEntity.setSuffix(excel.suffix()); | excelEntity.setSuffix(excel.suffix()); | ||||
excelEntity.setImportField(Boolean | |||||
.valueOf(PoiPublicUtil.getValueByTargetId(excel.isImportField(), targetId, "false"))); | |||||
getExcelField(targetId, field, excelEntity, excel, pojoClass); | getExcelField(targetId, field, excelEntity, excel, pojoClass); | ||||
if (getMethods != null) { | if (getMethods != null) { | ||||
List<Method> newMethods = new ArrayList<Method>(); | List<Method> newMethods = new ArrayList<Method>(); | ||||
@@ -103,15 +106,18 @@ public class ImportBaseService { | |||||
} | } | ||||
if (PoiPublicUtil.isCollection(field.getType())) { | if (PoiPublicUtil.isCollection(field.getType())) { | ||||
// 集合对象设置属性 | // 集合对象设置属性 | ||||
ExcelCollection excel = field.getAnnotation(ExcelCollection.class); | |||||
ExcelCollectionParams collection = new ExcelCollectionParams(); | ExcelCollectionParams collection = new ExcelCollectionParams(); | ||||
collection.setName(field.getName()); | collection.setName(field.getName()); | ||||
Map<String, ExcelImportEntity> temp = new HashMap<String, ExcelImportEntity>(); | Map<String, ExcelImportEntity> temp = new HashMap<String, ExcelImportEntity>(); | ||||
ParameterizedType pt = (ParameterizedType) field.getGenericType(); | ParameterizedType pt = (ParameterizedType) field.getGenericType(); | ||||
Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0]; | Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0]; | ||||
collection.setType(clz); | collection.setType(clz); | ||||
getExcelFieldList(targetId, PoiPublicUtil.getClassFields(clz), clz, temp, null); | |||||
getExcelFieldList(StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, | |||||
PoiPublicUtil.getClassFields(clz), clz, temp, null); | |||||
collection.setExcelParams(temp); | collection.setExcelParams(temp); | ||||
collection.setExcelName(field.getAnnotation(ExcelCollection.class).name()); | |||||
collection.setExcelName(PoiPublicUtil.getValueByTargetId( | |||||
field.getAnnotation(ExcelCollection.class).name(), targetId, null)); | |||||
additionalCollectionName(collection); | additionalCollectionName(collection); | ||||
excelCollection.add(collection); | excelCollection.add(collection); | ||||
} else if (PoiPublicUtil.isJavaClass(field)) { | } else if (PoiPublicUtil.isJavaClass(field)) { | ||||
@@ -121,9 +127,12 @@ public class ImportBaseService { | |||||
if (getMethods != null) { | if (getMethods != null) { | ||||
newMethods.addAll(getMethods); | newMethods.addAll(getMethods); | ||||
} | } | ||||
// | |||||
newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); | newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName())); | ||||
getAllExcelField(targetId, PoiPublicUtil.getClassFields(field.getType()), | |||||
excelParams, excelCollection, field.getType(), newMethods); | |||||
ExcelEntity excel = field.getAnnotation(ExcelEntity.class); | |||||
getAllExcelField(StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, | |||||
PoiPublicUtil.getClassFields(field.getType()), excelParams, excelCollection, | |||||
field.getType(), newMethods); | |||||
} | } | ||||
} | } | ||||
} | } | ||||
@@ -144,7 +153,7 @@ public class ImportBaseService { | |||||
public void getExcelField(String targetId, Field field, ExcelImportEntity excelEntity, | public void getExcelField(String targetId, Field field, ExcelImportEntity excelEntity, | ||||
Excel excel, Class<?> pojoClass) throws Exception { | Excel excel, Class<?> pojoClass) throws Exception { | ||||
excelEntity.setName(getExcelName(excel.name(), targetId)); | |||||
excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId, null)); | |||||
String fieldname = field.getName(); | String fieldname = field.getName(); | ||||
excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getSetMethod(fieldname)); | excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getSetMethod(fieldname)); | ||||
if (StringUtils.isNotEmpty(excel.importFormat())) { | if (StringUtils.isNotEmpty(excel.importFormat())) { | ||||
@@ -155,8 +164,8 @@ public class ImportBaseService { | |||||
} | } | ||||
public void getExcelFieldList(String targetId, Field[] fields, Class<?> pojoClass, | public void getExcelFieldList(String targetId, Field[] fields, Class<?> pojoClass, | ||||
Map<String, ExcelImportEntity> temp, List<Method> getMethods) | |||||
throws Exception { | |||||
Map<String, ExcelImportEntity> temp, | |||||
List<Method> getMethods) throws Exception { | |||||
ExcelImportEntity excelEntity = null; | ExcelImportEntity excelEntity = null; | ||||
for (int i = 0; i < fields.length; i++) { | for (int i = 0; i < fields.length; i++) { | ||||
Field field = fields[i]; | Field field = fields[i]; | ||||
@@ -170,34 +179,15 @@ public class ImportBaseService { | |||||
if (getMethods != null) { | if (getMethods != null) { | ||||
newMethods.addAll(getMethods); | newMethods.addAll(getMethods); | ||||
} | } | ||||
newMethods | |||||
.add(PoiReflectorUtil.fromCache(pojoClass).getSetMethod(field.getName())); | |||||
getExcelFieldList(targetId, PoiPublicUtil.getClassFields(field.getType()), | |||||
field.getType(), temp, newMethods); | |||||
ExcelEntity excel = field.getAnnotation(ExcelEntity.class); | |||||
newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getSetMethod(field.getName())); | |||||
getExcelFieldList(StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, | |||||
PoiPublicUtil.getClassFields(field.getType()), field.getType(), temp, | |||||
newMethods); | |||||
} | } | ||||
} | } | ||||
} | } | ||||
/** | |||||
* 判断在这个单元格显示的名称 | |||||
* | |||||
* @param exportName | |||||
* @param targetId | |||||
* @return | |||||
*/ | |||||
public String getExcelName(String exportName, String targetId) { | |||||
if (exportName.indexOf("_") < 0) { | |||||
return exportName; | |||||
} | |||||
String[] arr = exportName.split(","); | |||||
for (String str : arr) { | |||||
if (str.indexOf(targetId) != -1) { | |||||
return str.split("_")[0]; | |||||
} | |||||
} | |||||
return null; | |||||
} | |||||
public Object getFieldBySomeMethod(List<Method> list, Object t) throws Exception { | public Object getFieldBySomeMethod(List<Method> list, Object t) throws Exception { | ||||
Method m; | Method m; | ||||
for (int i = 0; i < list.size() - 1; i++) { | for (int i = 0; i < list.size() - 1; i++) { | ||||
@@ -215,8 +205,8 @@ public class ImportBaseService { | |||||
savefile.mkdirs(); | savefile.mkdirs(); | ||||
} | } | ||||
SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss"); | SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss"); | ||||
FileOutputStream fos = new FileOutputStream(path + "/" + format.format(new Date()) + "_" | |||||
+ Math.round(Math.random() * 100000) | |||||
FileOutputStream fos = new FileOutputStream( | |||||
path + "/" + format.format(new Date()) + "_" + Math.round(Math.random() * 100000) | |||||
+ (isXSSFWorkbook == true ? ".xlsx" : ".xls")); | + (isXSSFWorkbook == true ? ".xlsx" : ".xls")); | ||||
book.write(fos); | book.write(fos); | ||||
IOUtils.closeQuietly(fos); | IOUtils.closeQuietly(fos); | ||||
@@ -245,8 +235,8 @@ public class ImportBaseService { | |||||
* @param setMethods | * @param setMethods | ||||
* @param object | * @param object | ||||
*/ | */ | ||||
public void setFieldBySomeMethod(List<Method> setMethods, Object object, Object value) | |||||
throws Exception { | |||||
public void setFieldBySomeMethod(List<Method> setMethods, Object object, | |||||
Object value) throws Exception { | |||||
Object t = getFieldBySomeMethod(setMethods, object); | Object t = getFieldBySomeMethod(setMethods, object); | ||||
setMethods.get(setMethods.size() - 1).invoke(t, value); | setMethods.get(setMethods.size() - 1).invoke(t, value); | ||||
} | } | ||||
@@ -26,7 +26,7 @@ public class ExcelImportException extends RuntimeException { | |||||
private static final long serialVersionUID = 1L; | private static final long serialVersionUID = 1L; | ||||
private ExcelImportEnum type; | |||||
private ExcelImportEnum type; | |||||
public ExcelImportException() { | public ExcelImportException() { | ||||
super(); | super(); | ||||
@@ -50,6 +50,10 @@ public class ExcelImportException extends RuntimeException { | |||||
this.type = type; | this.type = type; | ||||
} | } | ||||
public ExcelImportException(String message, Throwable cause) { | |||||
super(message, cause); | |||||
} | |||||
public ExcelImportEnum getType() { | public ExcelImportEnum getType() { | ||||
return type; | return type; | ||||
} | } | ||||
@@ -22,7 +22,7 @@ package org.jeecgframework.poi.exception.excel.enums; | |||||
*/ | */ | ||||
public enum ExcelImportEnum { | public enum ExcelImportEnum { | ||||
GET_VALUE_ERROR("Excel 值获取失败"), VERIFY_ERROR("值校验失败"); | |||||
IS_NOT_A_VALID_TEMPLATE("不是合法的Excel模板"), GET_VALUE_ERROR("Excel 值获取失败"), VERIFY_ERROR("值校验失败"); | |||||
private String msg; | private String msg; | ||||
@@ -31,6 +31,7 @@ import java.util.Map; | |||||
import javax.imageio.ImageIO; | import javax.imageio.ImageIO; | ||||
import org.apache.commons.lang3.StringUtils; | |||||
import org.apache.poi.POIXMLDocumentPart; | import org.apache.poi.POIXMLDocumentPart; | ||||
import org.apache.poi.hssf.usermodel.HSSFClientAnchor; | import org.apache.poi.hssf.usermodel.HSSFClientAnchor; | ||||
import org.apache.poi.hssf.usermodel.HSSFPicture; | import org.apache.poi.hssf.usermodel.HSSFPicture; | ||||
@@ -432,5 +433,26 @@ public final class PoiPublicUtil { | |||||
} | } | ||||
return temp; | return temp; | ||||
} | } | ||||
/** | |||||
* 统一 key的获取规则 | |||||
* @param key | |||||
* @param targetId | |||||
* @return | |||||
*/ | |||||
public static String getValueByTargetId(String key, String targetId, String defalut){ | |||||
if (StringUtils.isEmpty(targetId) || key.indexOf("_") < 0) { | |||||
return key; | |||||
} | |||||
String[] arr = key.split(","); | |||||
String[] tempArr; | |||||
for (String str : arr) { | |||||
tempArr = str.split("_"); | |||||
if (targetId.equals(tempArr[1])) { | |||||
return tempArr[0]; | |||||
} | |||||
} | |||||
return defalut; | |||||
} | |||||
} | } |
@@ -0,0 +1,55 @@ | |||||
/** | |||||
* Copyright 2013-2015 JueYue (qrb.jueyue@gmail.com) | |||||
* | |||||
* Licensed under the Apache License, Version 2.0 (the "License"); | |||||
* you may not use this file except in compliance with the License. | |||||
* You may obtain a copy of the License at | |||||
* | |||||
* http://www.apache.org/licenses/LICENSE-2.0 | |||||
* | |||||
* Unless required by applicable law or agreed to in writing, software | |||||
* distributed under the License is distributed on an "AS IS" BASIS, | |||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |||||
* See the License for the specific language governing permissions and | |||||
* limitations under the License. | |||||
*/ | |||||
package org.jeecgframework.poi.util; | |||||
import java.util.Set; | |||||
import javax.validation.ConstraintViolation; | |||||
import javax.validation.Validation; | |||||
import javax.validation.Validator; | |||||
import javax.validation.ValidatorFactory; | |||||
/** | |||||
* HIBERNATE 校验工具类 | |||||
* @author JueYue | |||||
* @date 2015年11月11日 下午10:04:07 | |||||
*/ | |||||
public class PoiValidationUtil { | |||||
private final static Validator validator; | |||||
static { | |||||
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); | |||||
validator = factory.getValidator(); | |||||
} | |||||
public static String validation(Object obj) { | |||||
Set<ConstraintViolation<Object>> set = validator.validate(obj); | |||||
if (set.size() > 0) { | |||||
return getValidateErrMsg(set); | |||||
} | |||||
return null; | |||||
} | |||||
private static String getValidateErrMsg(Set<ConstraintViolation<Object>> set) { | |||||
StringBuilder builder = new StringBuilder(); | |||||
for (ConstraintViolation<Object> constraintViolation : set) { | |||||
builder.append(constraintViolation.getMessage()).append(","); | |||||
} | |||||
return builder.substring(0, builder.length() - 1).toString(); | |||||
} | |||||
} |