CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2005
    Posts
    33

    Lightbulb Export Jtable contents to Excel format

    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 :

    Code:
    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");
    	}
    }

  2. #2
    Join Date
    Sep 2004
    Posts
    247

    Re: Export Jtable contents to Excel format

    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.

  3. #3
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Export Jtable contents to Excel format

    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
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  4. #4
    Join Date
    Jun 2005
    Posts
    33

    Thumbs up Re: Export Jtable contents to Excel format

    Thanks for ur reply .It works fine.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured