Springboot 获取导入的Excel文件的sheet表 列名
场景:
需要判断传入的excel 文件 的列名是不是强一致匹对, 那么就需要拿出这些家伙
实现:
ExcelUtil.java
/**
* @Author: JCccc
* @Date: 2022-8-31 02:49
* @Description:
*/
public class ExcelUtil {
protected static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
private static final String SPLIT = ".";
public static Workbook getWorkbook(MultipartFile file) {
Workbook workbook=null;
try {
// 获取Excel后缀名
String fileName = file.getOriginalFilename();
if (StringUtils.isEmpty(fileName) || fileName.lastIndexOf(SPLIT) < 0) {
logger.warn("解析Excel失败,因为获取到的Excel文件名非法!");
return null;
}
String fileType = fileName.substring(fileName.lastIndexOf(SPLIT) + 1, fileName.length());
// 获取Excel工作簿
if (fileType.equalsIgnoreCase(XLS)) {
workbook = new HSSFWorkbook(file.getInputStream());
} else if (fileType.equalsIgnoreCase(XLSX)) {
workbook = new XSSFWorkbook(file.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
public static List<String> getSheetTitles( Workbook workbook) {
//拿第一个sheet表
Sheet sheet = workbook.getSheetAt(0);
// 校验sheet是否合法
if (Objects.isNull(sheet)) {
return null;
}
// 获取第一行数据(假如第一行就是列名)
Row sheetTitleRow = sheet.getRow(sheet.getFirstRowNum());
// 取出最后一列
short lastCellNum = sheetTitleRow.getLastCellNum();
List<String> sheetTitleList = new LinkedList<>();
for (int i = 0; i < lastCellNum; i++) {
//取出每一列的名
String cellValue = sheetTitleRow.getCell(i).getStringCellValue();
sheetTitleList.add(cellValue);
}
return sheetTitleList;
}
}
使用:
Workbook workbook = ExcelUtil.getWorkbook(file); if (Objects.nonNull(workbook)){ List<String> sheetTitlesFromFile = ExcelUtil.getSheetTitles(workbook); }
效果展示: