I have some excel files which i need to upload and save all the content in database.
In my excel files sometimes some column which is not mandatory is not present but in cases where it is mandatory it will be present
So How can i handle this situation single spring boot controller which run in all these 3 excel files?
For Example –
Excel File 1
Column1 | Column2 | Column3
data1 data 2 data 3
Excel File 2
Column1 | Column2 | Column3 | Column4
data1 data 2 data 3 data 4
Excel File 3
Column1 | Column2 | Column4
data1 data 2 data 2
My Implementation
for (int j = 0; j <= sheet.getLastRowNum(); j++) {
Row currentRow = sheet.getRow(j);
if (currentRow != null && currentRow.getCell(0)!=null) {
Student student = new Student();
// Common Fields which is in all the excel files
student.setId((int)Math.round(currentRow.getCell(1).getNumericCellValue()));
student.setName(currentRow.getCell(2).getStringCellValue());
// Rest of the fields (May be present in one excel but not present in other excel
vice-versa
}
}
Advertisement
Answer
This fix worked for me.
for (int z = 0; z < row.getLastCellNum() - 1; z++) {
String columnName = sheet.getRow(2).getCell(z).getStringCellValue(); // 2 is heading row
switch (columnName) {
case "Column 1":
student.set(currentRow.getCell(z).getStringCellValue())
break;
case "Column 2":
student.set(currentRow.getCell(z).getStringCellValue())
break;
default:
break;
}
}