Java/Write to excel


QUESTION: I have some JLabels and JTextFields in java.When the submit button is clicked ,these labels and fields values needs to be entered in a excel sheet.Question is : how to perform this on clicking submit?

ANSWER: Exporting directly to an excel file format is tricky, but you can easily export to a csv file which Excel can read from. The file that you output should look like:


Writing to a file is as easy as:
File file = ...;
PrintWriter writer = new PrintWriter(file);
writer.println(<column names>);
for(int i = 0; i < rows; i++) //rows is number of rows in your excel file
  writer.println(<row data>);
writer.close(); //important!

You can use the JFileChooser class if you want to show a save dialog to the user.

---------- FOLLOW-UP ----------

QUESTION: For Example : If the from look like

Label : Textfield

Name : xxx

Desg : yyy

Exp :  3

From this,how can i fetch all these textfields as row data?Is it possible?

For each text field  and label you can use:
String text = component.getText();

If you don't have all the text and label component (but you do have the parent component) variables stored you can also:

for(int i = 0; i < parent.getComponentCount(); i++)
  Component c = parent.getComponent(i);
  String text;
  if(c instanceof JTextField)
     text = ((JTextField)c).getText();
  else if(c instanceof JLabel)
     text = ((JLabel)c).getText();
  ...//write text to file.


All Answers

Answers by Expert:

Ask Experts


Artemus Harper


I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.


I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Washington State University

MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 All rights reserved.