public class ExcelUtil {
/**
* 校验excel表头 顺序及表头内容
*
* @param in
* @param clazz
* @return 表头异常信息提示
* @throws IOException
*/
public static String verifyExcelHeader(InputStream in, Class clazz) throws IOException {
String result;
try {
Workbook wb = new XSSFWorkbook(in);
result = ExcelUtil.checkExcelHeadLine(wb, clazz);
} catch (Exception e){
throw new BusinessException("verify excel header analysis is fail");
} finally {
if (null != in) {
in.close();
}
}
return result;
}
/**
* 校验上传excel表头信息
*
* @param wb
* @param clazz
* @return
*/
public static String checkExcelHeadLine(Workbook wb, Class clazz) throws NoSuchFieldException {
String result = null;
//通过class获取到使用@ExcelProperty注解配置的字段
Map<Integer, String> head = getIndexNameMap(clazz);
//获取第一个数据sheet页
Sheet sheet = wb.getSheetAt(0);
//获取sheet页第一行数据
Row row = sheet.getRow(0);
if (null != row && row.getLastCellNum() >= head.size()) {
for (int idx = 0; idx < row.getLastCellNum(); idx++) {
if (idx < head.size()) {
//获取表头内容
String value = row.getCell(idx).getStringCellValue();
if (StringUtils.isBlank(value) || !head.get(idx).equals(value)) {
result = String.format("上传excel表头行第%d列名称错误!", (idx + 1));
return result;
}
}
}
} else {
result = "上传excel表头与模板表头长度不一致!";
return result;
}
return null;
}
/**
* @param clazz
* @return
* @throws NoSuchFieldException
*/
public static Map<Integer, String> getIndexNameMap(Class clazz) throws NoSuchFieldException {
Map<Integer, String> result = new HashMap<>();
Field field;
//获取类中所有的属性
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
field = clazz.getDeclaredField(fields[i].getName());
field.setAccessible(true);
//获取根据注解的方式获取ExcelProperty修饰的字段
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty != null) {
//索引值
int index = excelProperty.index();
//字段值
String[] values = excelProperty.value();
StringBuilder value = new StringBuilder();
for (String v : values) {
value.append(v);
}
result.put(index, value.toString());
}
}
return result;
}
}