最近用Excel文件上傳,但是校驗的比較少,有的校驗就不對,我就自己寫了一個校驗,思路很簡單,就是上傳Excel 文件的標題和模板的標題是否一致,不一致就判斷上傳的不對,廢話不說,直接上代碼:
/**
* 自定義導出Excel數據註解
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
/**
* 導出到Excel中的名字.
*/
public String name() default "";
/**
* 日期格式, 如: yyyy-MM-dd
*/
public String dateFormat() default "";
/**
* 讀取內容轉表達式 (如: 0=男,1=女,2=未知)
*/
public String readConverterExp() default "";
/**
* 導出類型(0數字 1字符串)
*/
public ColumnType cellType() default ColumnType.STRING;
/**
* 導出時在excel中每個列的高度 單位爲字符
*/
public double height() default 14;
/**
* 導出時在excel中每個列的寬 單位爲字符
*/
public double width() default 16;
/**
* 文字後綴,如% 90 變成90%
*/
public String suffix() default "";
/**
* 當值爲空時,字段的默認值
*/
public String defaultValue() default "";
/**
* 提示信息
*/
public String prompt() default "";
/**
* 設置只能選擇不能輸入的列內容.
*/
public String[] combo() default {};
/**
* 是否導出數據,應對需求:有時我們需要導出一份模板,這是標題需要但內容需要用戶手工填寫.
*/
public boolean isExport() default true;
/**
* 另一個類中的屬性名稱,支持多級獲取,以小數點隔開
*/
public String targetAttr() default "";
/**
* 字段類型(0:導出導入;1:僅導出;2:僅導入)
*/
Type type() default Type.ALL;
public enum Type
{
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
public enum ColumnType
{
NUMERIC(0), STRING(1);
private final int value;
ColumnType(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
}
以下是判斷的關鍵代碼
/**
* 註解列表
*/
private List<Object[]> fields;
this.type = Excel.Type.IMPORT;
this.wb = WorkbookFactory.create(is);
List<T> list = new ArrayList<T>();
Sheet sheet = null;
String result = null ; //驗證導入Excel文件的標題頭是否正確
List<String> columnName = new ArrayList<>();// 獲取註解的標題
for (int i = 0; i < fields.size() ; i++) {
Object[] objects = fields.get(i);
Excel excel = (Excel) objects[1];//這塊是調文件,註解的標記的標題
columnName.add(excel.name());
}
if (StringUtils.isNotEmpty(columnName)){
result = this.checkExcelFormat(wb, columnName);
}
if (StringUtils.isNotNull(result)) {
throw new IOException(result);
}
以下是上面判斷的工具類:
/***
* 校驗導入Excel文件是否和模板一致
*/
private String checkExcelFormat(Workbook wb, List<String> columnName){
String result = null;
try {
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
if (row != null ) {
if (row.getLastCellNum() < columnName.size()){
result = "上傳文件中的列和模板不一致!";
}
int lastCellNum = row.getLastCellNum();
for (int idx = 0; idx < lastCellNum; idx++) {
String value = this.getCellValue(row, idx).toString();
if (!columnName.contains(value)){
return "上傳的文件與模板不一致!";
}
}
} else {
result = "上傳文件首行不能爲空!";
}
} catch (Exception ex) {
}
return result;
}
以上主要是判斷上傳的Excel文件和模板所用的列是否一致
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
return ResultEx.error(Constant.ERROR_CODE, "上傳文件只支持xls和xlsx文件後綴;", "");
}
以上主要是判斷你上傳的是否是Excel文件
參考於:https://blog.csdn.net/shy415502155/article/details/88661649