2

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);
}
1

1 Answer 1

3

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

wb.write(new FileOutputStream(excel));
Sign up to request clarification or add additional context in comments.

3 Comments

i made the change in line Row row = ws.createRow(rowNum); and added your line wb.write(new FileOutputStream(excel)); . and now its working but here i am taking all string values and if i want to submit string as well as integer value then what should i do bcoz currently when i am entering one integer value its showing string in excel..
Hm, I see you marked my answer. What I mean in my answer is: the change you made just affect the current XSSFWorkbook object in the memory. The XSSFWorkbook object is not the file, and whatever changes you made will not be written to the file automatically. Instead you have to manually call the write method. Hope this help.
That's a different thing though, I guess you can simply check the first character of the String (s1, s2... s4) and then call Integer.parseInt if it is a number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.