public ResponseEntity<Object> importPcpXlsx(MultipartFile xlsx) {
try {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(xlsx.getInputStream());
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
Row row;
Cell cell;
int i = 1;
List<String> number = new ArrayList<>();
while (true) {
if (xssfSheet.getRow(i) != null) {
row = xssfSheet.getRow(i);
cell = row.getCell(0);
if (cell.getSheet()
.getRow(0)
.getCell(0)
.getRichStringCellValue()
.getString()
.equals("Number".trim())) {
number.add(cell.getStringCellValue().trim());
log.info("number: " i ". № " cell.getStringCellValue());
}
} else {
i = 1;
break;
}
i ;
}
List<String> kpgz = new ArrayList<>();
while (true) {
if (xssfSheet.getRow(i) != null) {
row = xssfSheet.getRow(i);
cell = row.getCell(1);
if (cell.getSheet()
.getRow(0)
.getCell(1)
.getRichStringCellValue()
.getString()
.equals("kpgz".trim())) {
kpgz.add(cell.getStringCellValue().trim());
log.info("kpgz: " i ". " cell.getStringCellValue());
}
} else {
i = 1;
break;
}
i ;
}
I go through the columns and read all the lines under each column. But what if I have some columns will not come in xlxs file. That is, I need an option where I do not have to strictly specify columns. Please predict. In code Iread by columns, since columns have different types and should be processed differently. I need to do this so that I do not specify the number of columns in the column number code, as I did cell = row.getCell(0); or row.getCell(1) or row.getCell(2)
CodePudding user response:
Read the columns one by one and bind their type, then check data under these columns.
See example of type checking there: Best language to parse extremely large Excel 2007 files
If you can definetely identify column, it is not a problem. If not, you should think about changing api.