/**
*
*/
package de.tutorials;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
/**
* @author Tom
*
*/
public class JTableExample extends JFrame {
private JTable table;
private JButton btnExport;
private boolean exportInProgress;
public JTableExample() {
super("JTableExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Object[][] rowData = { { "1", "a", "c" }, { "2", "b", "b" },
{ "3", "f", "r" }, { "4", "q", "a" }, { "5", "w", "z" },
{ "6", "c", "a" }, { "7", "a", "q" } };
final Object[] columnHeaders = { "ID", "Header1", "Header2" };
table = new JTable(rowData, columnHeaders);
add(new JScrollPane(table), BorderLayout.CENTER);
btnExport = new JButton("Export to CSV");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!exportInProgress) {
exportInProgress = true;
new Thread() {
public void run() {
exportTableDataToCSV(table,
new File("c:/foooo.csv"));
exportInProgress = false;
}
}.start();
}
}
});
add(btnExport, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void exportTableDataToCSV(JTable table, File file) {
try {
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
TableModel model = table.getModel();
for (int clmCnt = model.getColumnCount(), rowCnt = model
.getRowCount(), i = 0; i < rowCnt; i++) {
for (int j = 0; j < clmCnt; j++) {
String value = model.getValueAt(i, j).toString();
bw.write(value);
bw.write(";");
}
bw.newLine();
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
new JTableExample();
}
}