Home > Back-end >  Apache POI workbook: getName returns null
Apache POI workbook: getName returns null

Time:12-04

I am trying to read cells for a xlsx file(provided by user) using Apache POI.

val workbook: org.apache.poi.ss.usermodel = ...
workbook.getName("cellname")

This works fine for one of the input file, but returns null for another file. Do we need to make any specific changes in input file first to make it compatible with this API?

CodePudding user response:

I think you should fetch data step by step. You can not directly fetch cell without any row/column or any sheet. First when you get workbook you need to check whether it contains any sheet or not. If it contains any sheet then after you should fetch row and after that you can fetch cell. You can refer below sample.

Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
System.out.println("Cell value is: "   cell.toString());

CodePudding user response:

To read cells from a Microsoft Excel file using Apache POI, you need to use the Sheet.getRow and Row.getCell methods. These methods allow you to access the cells in a sheet by their row and column indices, respectively.

Here is an example of how you can use the Sheet.getRow and Row.getCell methods to read the value of a cell in a Microsoft Excel file:

val workbook: Workbook = WorkbookFactory.create(new FileInputStream("myfile.xlsx"))
val sheet: Sheet = workbook.getSheetAt(0)
val row: Row = sheet.getRow(0)
val cell: Cell = row.getCell(0)
val cellValue: String = cell.getStringCellValue()

In this example, the WorkbookFactory.create method is used to create a Workbook object from the myfile.xlsx file. Then, the Workbook.getSheetAt method is used to get the first sheet in the workbook. The Sheet.getRow and Row.getCell methods are used to get the first row and first cell in the sheet, respectively. Finally, the Cell.getStringCellValue method is used to get the string value of the cell.

It is important to note that the Sheet.getRow and Row.getCell methods use zero-based indices, which means that the first row or cell in a sheet has an index of 0, the second row or cell has an index of 1, and so on. This means that if you want to read the value of a cell with a specific name, you will need to loop through the rows and cells in the sheet and compare the cell values to the name you are looking for.

Overall, to read cells from a Microsoft Excel file using Apache POI, you need to use the Sheet.getRow and Row.getCell methods to access the cells by their row and column indices. You do not need to make any specific changes to the input file to make it compatible with this API, but you will need to know the row and column indices of the cells you want to read.

  • Related