javacsvswingjtableexport-to-csv

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.


Solution

  • 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());