xls - Add New Column

Code to add new column in the xls workbook:


 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
public boolean addColumn(String sheetName,String colName){
 try{
  fis = new FileInputStream(path);
  workbook = new HSSFWorkbook(fis);
  int index = workbook.getSheetIndex(sheetName);
  if(index==-1)
   return false;
  HSSFCellStyle style = workbook.createCellStyle();
  style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
  style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

  sheet=workbook.getSheetAt(index);
  row = sheet.getRow(0);
  if (row == null)
   row = sheet.createRow(0);
  if(row.getLastCellNum() == -1)
   cell = row.createCell(0);
  else
   cell = row.createCell(row.getLastCellNum());
   cell.setCellValue(colName);
   cell.setCellStyle(style);

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

No comments:

Post a Comment