直接上代码
/**
* 检查 Excel文件表头信息
*
* @param file
* @param dataList
* @return
*/
public static boolean checkExcelHeaders(MultipartFile file, List<String> dataList) throws IOException {
InputStream inputStream = null;
try {
byte [] byteArr=file.getBytes();
inputStream = new ByteArrayInputStream(byteArr);
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
//获取 excel 第一行数据(表头)
Row row = sheet.getRow(0);
//存放表头信息
List<String> headerList = new ArrayList<>();
//算下有多少列
int colCount = sheet.getRow(0).getLastCellNum();
for (int j = 0; j < colCount; j++) {
Cell cell = row.getCell(j);
String cellValue = cell.getStringCellValue().trim();
if (!dataList.contains(cellValue)){
return false;
}
headerList.add(cellValue);
}
return headerList.size() == dataList.size();
}catch (Exception e){
e.printStackTrace();
return false;
}finally {
if (inputStream != null){
inputStream.close();
}
}
}
用法:
//这里的list就是理想中的excel表头,如果表头内容不一致或者表头字段个数不一致。就会false
public Result<?> upload(@RequestParam("file") MultipartFile file) {
boolean b = ExcelUtils.checkExcelHeaders(file, Arrays.asList("集团", "平台", "部门", "店铺", "年月", "费用项目", "金额", "分摊类型", "分摊依据", "订单号", "备注"));
if (!b) {
//自定义异常抛出
Assertion.fail("非上传模板,请查验");
}
}