Java JTable Model saveTModelToCSV(String fileName, JTable table)

Here you can find the source of saveTModelToCSV(String fileName, JTable table)

Description

Saves information from a table interface element to a file in CSV format.

License

Open Source License

Parameter

Parameter Description
fileName the name of the file
table table that to save

Exception

Parameter Description
IOException an exception

Declaration

public static void saveTModelToCSV(String fileName, JTable table)
        throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedWriter;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.OutputStreamWriter;
import javax.swing.JTable;
import javax.swing.table.TableModel;

public class Main {
    public static final String ENCODING = "UTF-8";

    /**//from w  w w .jav  a2s.c o m
     * Saves information from a table interface element to a file in CSV format.
     * Only information that is actually displayed at the moment is saved.
     * 
     * @param fileName the name of the file
     * @param table table that to save
     * @throws IOException 
     */
    public static void saveTModelToCSV(String fileName, JTable table)
            throws IOException {
        if (!fileName.endsWith(".csv"))
            fileName += ".csv";
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(fileName), ENCODING));
        TableModel model = table.getModel();
        for (int i = 0; i < table.getRowCount(); i++) {
            int index = table.convertRowIndexToModel(i);
            for (int j = 0; j < table.getColumnCount(); j++) {
                if (model.getColumnClass(j).equals(String.class))
                    out.write("\"" + model.getValueAt(index, j).toString()
                            + "\"");
                else
                    out.write(model.getValueAt(index, j).toString());
                if (j != model.getColumnCount() - 1)
                    out.write(",");
            }
            out.newLine();
        }
        out.close();
    }
}

Related

  1. getTableContent(TableModel table)
  2. insertTableModelListener( TableModel model, TableModelListener l, int index)
  3. insertTableModelListener(TableModel model, TableModelListener l, int index)
  4. makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA)
  5. modelIndexToDisplayIndex(JTable table, int modelIndex)
  6. setDataVector(DefaultTableModel model, Vector dataVector)
  7. tableModelToArray(JTable table)
  8. TableModelToList(JTable mode)
  9. toCsv(TableModel model)