Home

Export isi JTable ke file CSV

Mari berdiskusi bersama kami di Group Facebook Kurung Kurawal

JtableToCSV

Tutorial berikut bertujuan untuk meng-export isi dari JTable (dari Swing) menjadi file CSV. Tutorial ini saya buat berdasarkan pertanyaan di salah group pemrograman di Facebook.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tutorials;
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
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.PrintWriter;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
 
/**
 *
 * @author konglie
 */
public class JTableToCSV extends JFrame {
    public JTableToCSV(){
        super("JTable to CSV");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setMinimumSize(new Dimension(800, 600));
        initComponents();
        pack();
        this.setLocationRelativeTo(null);
        setVisible(true);
        genRandomData();
    }
 
    private JPanel toolbar;
    private JButton btnRandomData, btnToCSV;
    private JTable table;
    private void initComponents(){
        toolbar = new JPanel(new FlowLayout());
        toolbar.add(new JLabel("Operasi"));
 
        btnRandomData = new JButton("Generate Random Data");
        btnRandomData.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                genRandomData();
            }
        });
        toolbar.add(btnRandomData);
 
        btnToCSV = new JButton("Export to CSV");
        btnToCSV.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTableToCSV.saveCSV(table);
            }
        });
        toolbar.add(btnToCSV);
 
        getContentPane().add(toolbar, BorderLayout.NORTH);
 
        String[] cols = "Kolom 1, Kolom 2, Kolom 3, Kolom 4, Kolom 5".split(", ");
        DefaultTableModel tm = new DefaultTableModel(null, cols);
        table = new JTable(tm);
        table.setAutoCreateRowSorter(false);
 
        JScrollPane pane = new JScrollPane(table);
        getContentPane().add(pane, BorderLayout.CENTER);
 
        JLabel about = new JLabel("<html><center>&copy; ali LIM<br/>http://kurungkurawal.com</center></html>");
        about.setHorizontalAlignment(SwingConstants.CENTER);
        about.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        getContentPane().add(about, BorderLayout.SOUTH);
    }
 
    private void genRandomData(){
        DefaultTableModel tm = (DefaultTableModel) table.getModel();
        tm.setRowCount(0);
        int n = random(50,100);
        for(int i = 0; i < n; i++){
            tm.addRow(new Object[]{
                String.format("Data ke %s", i),
                String.format("Col %s - %s, %s", i, 2, random(10, 99)),
                String.format("Col %s - %s, %s", i, 3, random(10, 99)),
                String.format("Col %s - %s, %s", i, 4, random(10, 99)),
                String.format("Col %s - %s, %s", i, 5, random(10, 99))
            });
        }
    }
 
    public static void saveCSV(JTable table){
        DefaultTableModel model = (DefaultTableModel) table.getModel();
 
        JFileChooser chooser = new JFileChooser();
        int state = chooser.showSaveDialog(null);
        File file = chooser.getSelectedFile();
        if (file != null && state == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
                PrintWriter fileWriter = new PrintWriter(bufferedWriter);
                for (int i = 0; i < model.getRowCount(); i++) {
                    for (int j = 0; j < model.getColumnCount(); j++) {
                        Object o = model.getValueAt(i, j);
                        String s = (o == null ? "" : String.format("\"%s\"", o.toString()));
                        System.out.print(s);
                        bufferedWriter.write(s);
 
                        if(j < model.getColumnCount() - 1 ){
                            bufferedWriter.write(",");
                        } else {
                            bufferedWriter.write("\r\n");
                        }
                    }
                }
 
                fileWriter.close();
                JOptionPane.showMessageDialog(null, "Success");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Failure");
            }
        }
    }
 
    public static int random(int min, int max){
        return (int)( Math.random() * max + min);
    }
}

Method saveCSV() yang digunakan disini adalah modifikasi dari method yang ditanyakan di group facebook tersebut.

Download file jar demo nya disini.