Is there a way to save j table data to excel by using eclipse? I have a program that I made using eclipse and I would like to save the data that I input from the Program, from the j table and then to a 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.