user3343658
user3343658

Reputation: 80

How to add a row in an existing Excel file using Java?

How to add a row in an existing Excel file using Java? I tried using this code but it's not working. Please tell me what corrections I need to do.

try {
  String s1 ,s2,s3,s4;
  s1 = jTextField1.getText();
  s2 = jTextField2.getText();
  s3 = jTextField3.getText();
  s4 = jTextField4.getText();
  FileInputStream fis =  null;
  File excel =  new File ("E:\\two\\record.xlsx");
  fis = new FileInputStream(excel);
  XSSFWorkbook wb = new XSSFWorkbook(fis);
  XSSFSheet ws = wb.getSheet("cmss");
  int rowNum = ws.getLastRowNum() + 1;
  Row row = ws.createRow(4);
  String[] s = new String[4];
  s[0] = s1;
  s[1] = s2;
  s[2] = s3;
  s[3] = s4;
  for (int i = 0; i < 4; i++) {
    Cell cell = row.createCell(i);
    cell.setCellValue(s[i]);
  }
  jTextField1.setText("");
  jTextField2.setText("");
  jTextField3.setText("");
  jTextField4.setText("");
} catch (FileNotFoundException ex) {
  Logger.getLogger(Addxl.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
  Logger.getLogger(Addxl.class.getName()).log(Level.SEVERE, null, ex);
}

Upvotes: 2

Views: 6695

Answers (1)

tungd
tungd

Reputation: 14887

Did you write the file out after adding rows? For example:

wb.write(new FileOutputStream(excel));

Upvotes: 3

Related Questions