1

I have a requirement, where dynamic data comes from excel, and I need to extract header(column) names(1st row) into array list.

file =new FileInputStream(new File("excel file")); HSSFWorkbook workbook = new XSSFWorkbook(file);

Any input greatly appreciated, I am very new to java programming.

Thanks

1
  • Grab the first sheet, grab the first row, iterate over all the cells, grab/format the values and return? Commented Apr 2, 2020 at 11:42

1 Answer 1

1

Do it as follows:

// Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook(file);

// Get the first sheet from the workbook
XSSFSheet firstSheet = workbook.getSheetAt(0);

// Get the first row from the sheet
Row row = firstSheet.getRow(0);

// Create a List to store the header data
ArrayList<String> headerData = new ArrayList<>();

// Iterate cells of the row and add data to the List
for (Cell cell : row) {
    switch (cell.getCellType()) {
    case NUMERIC:
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            DataFormatter dataFormatter = new DataFormatter();
            headerData.add(dataFormatter.formatCellValue(cell));
        } else {
            headerData.add(String.valueOf(cell.getNumericCellValue()));
        }
        break;
    case STRING:
        headerData.add(cell.getStringCellValue());
        break;
    case BOOLEAN:
        headerData.add(String.valueOf(cell.getBooleanCellValue()));
        break;
    default:
        headerData.add("");
        break;
    }
}

// Print the List
System.out.println(headerData);

Feel free to comment in case of any doubt/issue.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks Arvind for the quick replay, does the statement needs to be type casted? , as header is string array and cell is an object. I am getting " The method add(string) in the type ArrayList<String> is not applicable for the arguments (cell)
the statement is throwing out the Exception: headerData.add(cellIterator.next())
You'd probably be better off either checking the cell type, or using a class like DataFormatter - this code will fail for headers like dates or numbers!
Thanks, @Gagravarr for the suggestion. I've updated the code to incorporate the same.
Thanks Arvind, that was great help
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.