在实际excel读取中,会出现很多后缀为xlsx 内容实际确为xls的情况,反之亦然。所以光利用文件后缀名读取excel文件时,会有偏差。
本文则利用魔数以及结合文件后缀名共同判断excel文件类型,达到文件识别基本无误的情况
/**
* excel 类型获取 注意fileMagic 仅3.17之后的版本才有
*
* @param inputStream
* @return
* @author zms
*/
public static String checkExcelFileType(InputStream inputStream) {
String type = "";
try {
/**
* 优化excel类型判断
* 注意可能会获取报错 getFileMagic() only operates on streams which support mark(int)
* 原因InputStream中markSupported方法返回值为false造成的,BufferedInputStream中返回值是true,所以改为InputStream is = new BufferedInputStream(multipartFile.getInputStream())
*/
FileMagic fileMagic = FileMagic.valueOf(inputStream);
if (Objects.equals(fileMagic, FileMagic.OLE2)) {
return EXCEL2003;
} else if (Objects.equals(fileMagic, FileMagic.OOXML)) {
return EXCEL2007;
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return type;
}
/**
* 根据名字和流判断文件类型
*
* @param fileName
* @param inputStream
* @return
*/
public static String getExcelType(String fileName, InputStream inputStream) {
String excelType = checkExcelFileType(inputStream);
if ("error".equals(excelType)) {
if (LogicUtil.isNotEmpty(fileName)) {
if (fileName.endsWith(EXCEL2003)) {
return EXCEL2003;
} else if (fileName.endsWith(EXCEL2007)) {
return EXCEL2007;
}
}
}
return excelType;
}