xls - Write Into Cell

Code to write into a cell:


 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
public boolean setCellData(String sheetName,String colName,int rowNum, String data){

 try{
  fis = new FileInputStream(path);
  workbook = new HSSFWorkbook(fis);

  if(rowNum<=0)
   return false;

  int index = workbook.getSheetIndex(sheetName);
  int colNum=-1;
  if(index==-1)
   return false; 
  
  sheet = workbook.getSheetAt(index);
  row=sheet.getRow(0);
  
  for(int i=0;i<row.getLastCellNum();i++){
   if(row.getCell(i).getStringCellValue().trim().equals(colName))
    colNum=i;
  }
  if(colNum==-1)
   return false;

  sheet.autoSizeColumn(colNum);
  row = sheet.getRow(rowNum-1);

  if (row == null)
   row = sheet.createRow(rowNum-1);
   cell = row.getCell(colNum); 
   if (cell == null)
    cell = row.createCell(colNum);
    cell.setCellValue(data);

  fileOut = new FileOutputStream(path);
  workbook.write(fileOut);
  fileOut.close(); 
 }catch(Exception e){
  e.printStackTrace();
  return false;
 }
 return true;
}