/*
* FileExport.java
*/
package exportUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
import javax.swing.JTable;
/**
* Export table tableHeaders and data to a CSV file
*
*/
public class CsvExport {
private JTable tableResult;
private String[] tableHeaders;
/**
* Creates a new instance of FileExport
*
* @param tableHeaders[] the headers from the JTable
* @param tableResult the JTable object.
*/
public CsvExport(String[] tableHeaders, JTable tableResult) {
this.tableHeaders = tableHeaders;
this.tableResult = tableResult;
}
/**
* Write table tableHeaders and data to a file
* selected from a file chooser.
*
* @return null if no exception is thrown, otherwise the description of the exception
*/
public String writeCSV() {
try {
JFileChooser fileSelection = new JFileChooser();
SimpleFileFilter csvFilter = new SimpleFileFilter("csv", "Komma getrennte Werteliste");
fileSelection.setAcceptAllFileFilterUsed(false);
fileSelection.addChoosableFileFilter(csvFilter);
fileSelection.showDialog(null, "Exportieren");
try {
String fileName = fileSelection.getSelectedFile().toString();
if (!fileName.substring(fileName.length()-4).toLowerCase().equals(".csv")) {
fileName += ".csv";
}
File exportFile = new File(fileName);
if (exportFile != null){
PrintWriter pw = new PrintWriter(new FileWriter(exportFile.getAbsolutePath()));
int rows = tableResult.getRowCount();
int columns = tableResult.getColumnCount();
for (int i = 0; i < columns; i++){
pw.print(tableHeaders[i]);
if (i < columns-1) pw.print(";");
}
pw.println();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++){
pw.print(tableResult.getValueAt(i, j).toString());
if (j < columns-1) pw.print(";");
}
pw.println();
}
pw.close();
}
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
return null;
} catch (Exception ex) {
ex.printStackTrace();
return(ex.toString());
}
}
}