验证模板:
/**
* 校验模板
* @param sheet 表
*/
private void checkExcelTemplate(Sheet sheet) {
int column = 0;
String[] fields = {"aa", "bb", "cc", "dd", "ee", "ff"};
try {
for (String field : fields) {
String title = Abc.class.getDeclaredField(field).getAnnotation(ExcelField.class).title();
if (!StringUtils.equals(getCellValue(sheet, 0, column++), title)) {
throw new BusinessException();
}
}
} catch (Exception e) {
log.error("模板不正确", e);
throw new BusinessException("模板不正确");
}
}
获取单元格的值:
/**
* java pio 获取单元格的值
*
* @param sheet 表
* @param rowIndex 行号
* @param columnIndex 列号
* @return 单元格值
*/
private String getValue(Sheet sheet, int rowIndex, int columnIndex) {
String cellValue;
Row row = sheet.getRow(rowIndex);
if (row == null) {
return StringUtils.EMPTY;
}
Cell cell = row.getCell(columnIndex);
if (cell == null) {
return StringUtils.EMPTY;
}
cell.setCellType(Cell.CELL_TYPE_STRING);
boolean isMerge = ExcelUtils.isMergedRegion(sheet, rowIndex, columnIndex);
if (isMerge) {
cellValue = ExcelUtils.getMergedRegionValue(sheet, rowIndex, columnIndex);
} else {
cellValue = cell.getStringCellValue();
}
return StringUtils.trim(cellValue);
}