Good afternoon experts, I have a problem with a project that consists of reading an excel file and validating the data by columns, I have managed to read the file without problems and also validations (through regular expressions) through the library Apache POI the detail is that I can only read columns by column index (example index 0 = column 1, index 1 = column 2 etc) with the method getColumnIndex()
the problem is that I need to read them by their column name instead of its index since the file to read will tend to change the position of the columns, there is some method to solve this, I have tried with:
columnIndex = cell.getSheet().getRow(rowIndex).getCell(0).getRichStringCellValue().toString();
But I can only read the entire row but not all the columns and rows.
I attach the code I use to read the files:
Workbook workbook = WorkbookFactory.create(new FileInputStream("C:\archivo.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
totalRows = sheet.getPhysicalNumberOfRows();
System.out.println("Número total de filas: " + totalRows);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
rowIndex = row.getRowNum();
int rowIndex2 = rowIndex +1;
if (rowIndex2 < 8) {
continue;
}
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
columnIndex = cell.getColumnIndex();
switch (columnIndex) {
case 0:
columnName = "columna 1";
//System.out.println(columnName+" -> " + rowIndex);
break;
case 1:
columnName = "Columna 2";
break;
case 2:
columnName = "Columna 3";
break;
}
value = this.getValue(cell);
valid = this.isValid(columnIndex, value);
if (valid && (value != "")) {
continue;
}
if (value!="")
{
System.out.print("Valorno válido: " + columnName + " - " + rowIndex2);
System.out.println(" -> valor no válido: " + value);
}
}
}
return procesarBTR();
}
private String getValue(Cell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
// return columnName;
return "";
case Cell.CELL_TYPE_BOOLEAN:
return "CELL_TYPE_BOOLEAN";
// return cell.getStringCellValue();
case Cell.CELL_TYPE_ERROR:
return "CELL_TYPE_ERROR";
case Cell.CELL_TYPE_FORMULA:
/*switch (cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
case Cell.CELL_TYPE_NUMERIC:
return cell.getNumericCellValue() + "";
default:
return "";}*/
return cell.getStringCellValue();
case Cell.CELL_TYPE_NUMERIC:
return fmt.formatCellValue(cell);
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
default:
return "valor desconocido";
}
}
Code that performs validations . . .