Click to See Complete Forum and Search --> : Export Jtable contents to Excel format


kaaj
June 6th, 2005, 05:45 AM
Hi,
I need to export the values in the JTable component to be exported to MS - excel. Currently it is successfully exported as text file, but when I open in Ms-Excel, the contents are displayed in single cell. Here is the code I have used :

int state = chooser.showSaveDialog(null);
File file = chooser.getSelectedFile();
if (file != null && state == JFileChooser.APPROVE_OPTION)
{
try
{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file,true));
PrintWriter fileWriter = new PrintWriter(bufferedWriter);

for(int i=0; i<model.getRowCount(); ++i)
{
for(int j=0; j<model.getColumnCount(); ++j)
{
String s = model.getValueAt(i,j).toString();
fileWriter.print(s);
}
fileWriter.println("");
}
fileWriter.close();
JOptionPane.showMessageDialog(null, "Success");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Failure");
}
}

Davey
June 6th, 2005, 01:54 PM
You could try outputting them in CSV format i.e.

a,b,c
d,e,f
g,h,i

If you save it with a .csv extension I think Excel will then open it correctly.

dlorde
June 6th, 2005, 03:21 PM
Davey is right - the default import format for Excel is CSV (comma-delimited) format in .csv text files.

Each field should be separated from the next by commas, and each line should be separated from the next by a newline character ('\n'), or return and newline ("\r\n").

If any field contains the delimiter or a newline, surround it with double-quotes.

Use tabs as the delimiters for copy & pasting from the clipboard.

Today, most software exists, not to solve a problem, but to interface with other software...
I. O. Angell

kaaj
June 7th, 2005, 12:22 AM
Thanks for ur reply .It works fine.