How to export data from JTable to CSV
I am just having problems starting a bit of code to extract values from JTable so that I can eventually say them as a CSV file for viewing on Excel. Currently I have a JTable created using the following code:
package com.alpha;
import javax.swing.*;
import java.awt.*;
public class JTableComponent{
public static void main(String[] args)
{
new JTableComponent();
}
public JTableComponent(){
JFrame frame = new JFrame("Whiteboard Test");
JPanel panel = new JPanel();
String data[][] = {{"Company A","1000","1"},{"Company B","2000","2"},
{"Company C","3000","3"},{"Company D","4000","4"}};
String col[] = {"Company Name","Shares","Price"};
JTable table = new JTable(data,col);
panel.add(ta开发者_如何学Cble,BorderLayout.CENTER);
frame.add(panel);
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I have started a new class that will be called whenever the "Export to CSV" button is pressed. I will implement the button listeners etc at a later stage, right now I would like a few pointers on how to create the for look that will go through the columns and rows looking for the values contained in them. Just a note, the JTable will be scalable, the current JTable is just for test purposes. I know there are APIs available such as the Apache one however I would prefer not to use them.
package com.alpha;
public class Exporter extends JTableComponent
{
public changeToCSV(){
}
public changeToCSV()
{
for(int j = 0; j < table.getColumnCount(); j++) {
}
}
I am having trouble deciding what the constructor should expect to receive. Many thanks for your help in advance!
I used following method in to extract data as csv from JTable, hopefully this will be helpful to someone
public static boolean exportToCSV(JTable tableToExport,
String pathToExportTo) {
try {
TableModel model = tableToExport.getModel();
FileWriter csv = new FileWriter(new File(pathToExportTo));
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;
}
Maybe you want to consider using TSV (Tab-Separated Values) as an alternative to comma-separated value (CSV) format, which often causes difficulties because of the need to escape commas. Here's a simple java tutorial that implements a JTable then exports it to MS Excel file using TSV format: How To Export Records From JTable To MS Excel
Below is the exported excel file (manually adjusted column widths)
The Exporter class method definitions are invalid. You need to include return types in order for this code to compile (I presume this is what you mean when you mention about what the constructor should return).
For a simple implementation you could consider returning a String[][] which you could then translate into csv data in a doubly nested loop. I have implemented something in the past where I had a structure similar to:
ExportAction
|
|--> ExportDestination
|--> ExportFormatter
The ExportAction
is an implementation of javax.swing.Action
and is associated with the "Export to csv" button. It references two classes:
ExportDestination
: The logical destination for the csv data. This interface offers a method createWriter() that is called by the action to create a "sink" which to squirt the csv data down. A concrete implementation ofExportDestination
is FileDestination, but I also implemented others such asClipboardDestination
.ExportFormatter
: Responsible for translating the table rows into csv data. I chose to do this one row at a time: TheExportAction
would iterate over each row to export callingexportFormatter.writeTableRow
and passing in the writer created from the export destination. This gave me the flexibility to decide which rows to export (e.g. those currently visible / currently selected / all rows).
So in answer to your original question I didn't return anything from my various export methods. Instead, when the action was invoked I would prompt the user to select parameters (e.g. file name) which I would then set before invoking my export routine.
Hope that helps.
Exporter could be made into a helper class. However, since it appears you want to export any JTable what you could do to make things simple would be to switch to a utility method.
public class CSVExporterUtils{
public static void exportToCSV( JTable tableToExport, String pathToExportTo ){
// Pseudocode below
/*
Open file and test if valid path
Loop through each table line
Loop through each column
Get value at line, column
Add value to StringBuilder plus a comma
Write contents of StringBuilder to file
And add return using System.getProperty("line.separator")
End Loop
Close file
*/
}
}
You could then call this method as follows:
CSVExporterUtils.exportToCSV( myJTable, "c:/myExportedData.csv" );
精彩评论