17

How to get the column names in an Excel file using Apache POI, to make sure that the columns are ordered as expected.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498
  • 5
    Do you mean "A", "B", ...? If not, what do you mean by column names? Columns are normally "named" by putting names in a top row. – Ed Staub Nov 20 '11 at 15:05
  • 3
    @Ed Staub is it possible to get "A" and "B", i have a similar requirement – kavinder Nov 05 '14 at 12:46

4 Answers4

35

There is a convenience method for this:

CellReference.convertNumToColString(cell.getColumnIndex());

To get the full name:

private static String getCellName(Cell cell)
{
    return CellReference.convertNumToColString(cell.getColumnIndex()) + (cell.getRowIndex() + 1);
}
wvdz
  • 16,251
  • 4
  • 53
  • 90
9

Or this:

cell.getSheet().getRow(0).getCell(currentcellIndex)
    .getRichStringCellValue().toString()

Row indexes start from 0.

halfer
  • 19,824
  • 17
  • 99
  • 186
Josh
  • 138
  • 1
  • 2
5

Apache POI, translating Excel column number to letter

      FileInputStream fis = new FileInputStream(
      new File("D:\\workspace\\Writesheet.xlsx"));
      @SuppressWarnings("resource")
      XSSFWorkbook workbook = new XSSFWorkbook(fis);
      XSSFSheet spreadsheet = workbook.getSheetAt(0);

      int lastcell=spreadsheet.getRow(0).getLastCellNum();
      //Non empty Last cell Number or index return

      for(int i=0;i<=lastcell;i++)
      {
          try
          {
              System.out.println(CellReference.convertNumToColString(i));
          }catch(Exception e)
          {}
      }
      fis.close();
halfer
  • 19,824
  • 17
  • 99
  • 186
Chetan Bhagat
  • 610
  • 6
  • 21
1

To get cell name:

String cellName = new CellAddress(intRow, intCol).toString();