Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save from JTable to CSV or Excel?

Is there a way to save JTable data to excel? I would like to save the data that I input from the program, from the table and then to a CSV file.

I would like to have it so that there is a button that will then save the inputted data from the GUI into the table and then to the CSV file.

like image 699
Looth Avatar asked Nov 14 '22 18:11

Looth


1 Answers

This may help you:-

Method to write to a csv file.

public static void exportToCSV(JTable table,
        String path) {

    try {

        TableModel model = table.getModel();
        FileWriter csv = new FileWriter(new File(path));

        for (int i = 0; i < model.getColumnCount(); i++) {
            csv.write(model.getColumnName(i) + ",");
        }

        csv.write("\n");

        for (int i = 0; i < model.getRowCount(); i++) {
            for (int j = 0; j < model.getColumnCount(); j++) {
                csv.write(model.getValueAt(i, j).toString() + ",");
            }
            csv.write("\n");
        }

        csv.close();
    } catch (IOException e) {
       System.out.println("Error "+e);
    }
}

For reading and showing it to a JTable you can use OpenCSV.

CSVReader reader = new CSVReader(new FileReader("file.csv")); 
List list = reader.readAll();
JTable table = new JTable(list.toArray());
like image 84
JFan Avatar answered Nov 30 '22 22:11

JFan