Here you can find the source of saveTModelToCSV(String fileName, JTable table)
Parameter | Description |
---|---|
fileName | the name of the file |
table | table that to save |
Parameter | Description |
---|---|
IOException | an exception |
public static void saveTModelToCSV(String fileName, JTable table) throws IOException
//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(); } }