CSV to TableModel PDF Print E-mail
Written by Charles   
Thursday, 10 June 2010 19:32

Here's a simple way to turn a CSV file into a TableModel suitable for displaying in a JTable in Swing. The source is HERE

import java.io.*;

import java.util.*;

import javax.swing.*;
import javax.swing.table.*;


public class Csv2TableModel {
    /**
     * Rudimentary quick and dirty demo code
     *
     * @param args (Not used)
     */
    public static void main(String[] args) {
        try {
            String datafile = "data.txt";
            FileReader fin = new FileReader(datafile);
            DefaultTableModel m = createTableModel(fin,
                    new Vector<Object>(Arrays.asList(
                            new String[] { "a", "b", "c" })));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(new JTable(m)));
            f.setSize(200, 300);
            f.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     *
     * @param in A CSV input stream to parse
     * @param headers A Vector containing the column headers. If this is null, it's assumed
     * that the first row contains column headers
     *
     * @return A DefaultTableModel containing the CSV values as type String
     */
    public static DefaultTableModel createTableModel(Reader in,
            Vector<Object> headers) {
        DefaultTableModel model = null;
        Scanner s = null;

        try {
            Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
            s = new Scanner(in);

            while (s.hasNextLine()) {
                rows.add(new Vector<Object>(Arrays.asList(s.nextLine()
                                .split("\\s*,\\s*", -1))));
            }

            if (headers == null) {
                headers = rows.remove(0);
                model = new DefaultTableModel(rows, headers);
            } else {
                model = new DefaultTableModel(rows, headers);
            }

            return model;
        } finally {
            s.close();
        }
    }
}
Comments
Search
Only registered users can write comments!

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated ( Wednesday, 20 July 2011 16:45 )