Link to home
Start Free TrialLog in
Avatar of Couturier
Couturier

asked on

How to save the content of a JTable to a csv file ?

Hello,

Java.
How to save the content of a JTable to a csv file ?
Java source code welcome.

Avatar of anokun7
anokun7

/******************************************
SOURCE: http://forums.java.net/jive/thread.jspa?threadID=23336
******************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.table.*;
public class ExcelExporter  {
    public ExcelExporter() { }
    public void exportTable(JTable table, File file) throws IOException {
        TableModel model = table.getModel();
        FileWriter out = new FileWriter(file);
       
        for(int i=0; i < model.getColumnCount(); i++) {
            out.write(model.getColumnName(i) + "\t");
        }
        out.write("\n");
        for(int i=0; i< model.getRowCount(); i++) {
            for(int j=0; j < model.getColumnCount(); j++) {
                out.write(model.getValueAt(i,j).toString()+"\t");
            }
            out.write("\n");
        }
        out.close();
        System.out.println("write out to: " + file);
    }
   
   
    public static void main(String[] args) {
        String[][] data = {
            { "Housewares",  "$1275.00" },
            { "Pets",         "$125.00" },
            { "Electronics", "$2533.00" },
            { "Mensware",     "$497.00" }
        };
        String[] headers = { "Department", "Daily Revenue" };

        JFrame frame = new JFrame("JTable to Excel Hack");
        DefaultTableModel model = new DefaultTableModel(data,headers);
        final JTable table = new JTable(model);
        JScrollPane scroll = new JScrollPane(table);

        JButton export = new JButton("Export");
        export.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    ExcelExporter exp = new ExcelExporter();
                    exp.exportTable(table, new File("results.xls"));
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                    ex.printStackTrace();
                }
            }
        });

        frame.getContentPane().add("Center",scroll);
        frame.getContentPane().add("South",export);
        frame.pack();
        frame.setVisible(true);
    }
}
ASKER CERTIFIED SOLUTION
Avatar of anokun7
anokun7

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It's easier if you don't implement it yourself. Two of the best libraries I've found:
http://opencsv.sourceforge.net/

and
http://sourceforge.net/projects/javacsv/

The first one has better documentation, so that's what I use. it handles all issues when text contains the seperator. for example, exporting the valuse 'Cornelius, Riaan' and 'Developer' to a csv file will produce:
"Cornelius, Riaan", Developer

It also contains a reader that deals with this issues.
Avatar of Couturier

ASKER

to riaancornelius:

http://opencsv.sourceforge.net/
CSVWriter need strings.
From a JTable you need to browse the JTable.
With or without opencsv you need to browse the JTable.
Dont help from my point of view.

I dont have tried :
http://sourceforge.net/projects/javacsv/
I have the feeling it's the same.
Maybe I am wrong.

Anyway thanks for your answer.
anokun7:

I accept your comment like the solution solution.

Here my source code.
I have made some change from yours.
I have added a if because if there is nothing in the cell a exception occure.
I have change the "\t" to ","
and teh FileWriter  with a PrintWriter.

Thanks,
You have the points.

                  for (int i = 0; i < dtm.getRowCount(); i++) {
                        line = "";
                        for (int j = 0; j < dtm.getColumnCount(); j++) {
                              Object rr;
                              rr = dtm.getValueAt(i, j);
                              if (dtm.getValueAt(i, j) == null) {
                                    line += ",";
                              } else {
                                    line += dtm.getValueAt(i, j) + ",";
                              }
                        }
                        writer.println(line);
                  }
                  writer.close();