Home > Enterprise >  How to save from JTable to CSV or Excel
How to save from JTable to CSV or Excel

Time:10-26

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 JTable 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 jform into the jtable and then to the CSV file.

CodePudding user response:

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

Hope it helps!

CodePudding user response:

There is no 'magic function' of a JTable that I know of that will do this. JTable is a UI component, and what you're asking for is a data function, not a user interface function. And it doesn't have much to do with eclipse, which is just the IDE one uses to write the code.

I think what you may be looking for is the model on which the JTable is based. The first solution that occurs to me is to alter that model code to have a method that will write out the data in the format you want; then a(nother) button on your UI would invoke this method on the model to write out the data when the user chooses. There are likely other ways you might get this done, but that seems the most straightforward and easiest.

CodePudding user response:

You can try this code:

public static boolean convertToCSV(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();
    return true;
} catch (IOException e) {
    e.printStackTrace();
}
return false;
}
  • Related