xls - Get Cell Data

Code to get the cell data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// returns the data from a cell
public String getCellData(String sheetName,String colName,int rowNum){
 try{
  if(rowNum <=0)
   return "";
 
 int index = workbook.getSheetIndex(sheetName);
 int col_Num=-1;
 if(index==-1)
  return "";
 
 sheet = workbook.getSheetAt(index);
 row=sheet.getRow(0);
 for(int i=0;i<row.getLastCellNum();i++){
  //System.out.println(row.getCell(i).getStringCellValue().trim());
  if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
   col_Num=i;
 }
 if(col_Num==-1)
  return "";
 
 sheet = workbook.getSheetAt(index);
 row = sheet.getRow(rowNum-1);
 if(row==null)
  return "";
 cell = row.getCell(col_Num); 
 if(cell==null)
  return "";
 if(cell.getCellType()==Cell.CELL_TYPE_STRING)
    return cell.getStringCellValue();
 else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){
    
    String cellText  = String.valueOf(cell.getNumericCellValue());
    if (HSSFDateUtil.isCellDateFormatted(cell)) {
            // format in form of M/D/YY
     double d = cell.getNumericCellValue();

     Calendar cal =Calendar.getInstance();
     cal.setTime(HSSFDateUtil.getJavaDate(d));
           cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
           cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
                       cal.get(Calendar.MONTH)+1 + "/" + cellText;
          }    
    return cellText;
   }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
       return ""; 
   else 
    return String.valueOf(cell.getBooleanCellValue()); 
 }
 catch(Exception e){  
  e.printStackTrace();
  return "row "+rowNum+" or column "+colName +" does not exist in xls";
 }
}