How to extract Excel file header names into array list using POI?

user2927486 :

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

Arvind Kumar Avinash :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=389022&siteId=1