use of net.sourceforge.sqlexplorer.dataset.mapdb.SqlExplorerTalendDataSet in project tdq-studio-se by Talend.
the class ExportCSVAction method run.
/**
* Main method. Prompt for file name and save table contents to csv file.
*/
@Override
public void run() {
final CsvExportOptionsDlg dlg = new CsvExportOptionsDlg(_table.getShell());
if (dlg.open() != Window.OK) {
return;
}
// let's show the fancy wait cursor..
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
// create new file
File file = new File(dlg.getFilename());
if (file.exists()) {
// overwrite existing files
file.delete();
}
file.createNewFile();
PrintStream writer = new PrintStream(file, dlg.getCharacterSet());
// $NON-NLS-1$
StringBuffer buffer = new StringBuffer("");
// get column header and separator preferences
String columnSeparator = dlg.getDelimiter();
boolean includeColumnNames = dlg.includeHeaders();
boolean rtrim = dlg.trimSpaces();
boolean quote = dlg.quoteText();
String nullValue = dlg.getNullValue();
boolean isExportAll = dlg.isExportAll();
// check if there is somethign in our table
DataSet dataSet = (DataSet) _table.getData();
if (!isExportAll && SqlExplorerTalendDataSet.class.isInstance(dataSet)) {
dataSet = ((SqlExplorerTalendDataSet) dataSet).getCurrentPageDataSet();
}
if (dataSet == null) {
return;
}
// export column names if we need to
if (includeColumnNames) {
DataSet.Column[] columns = dataSet.getColumns();
for (int i = 0; i < columns.length; i++) {
if (i != 0) {
buffer.append(columnSeparator);
}
buffer.append(columns[i].getCaption());
}
writer.println(buffer.toString());
}
// export column data
int columnCount = _table.getColumnCount();
for (int i = 0; i < dataSet.getRowCount(); i++) {
// $NON-NLS-1$
buffer = new StringBuffer("");
DataSetRow row = dataSet.getRow(i);
for (int j = 0; j < columnCount; j++) {
Object o = row.getRawObjectValue(j);
String t = o == null ? nullValue : o.toString();
if (rtrim) {
t = TextUtil.rtrim(t);
}
if (quote && o instanceof String) {
// $NON-NLS-1$
buffer.append("\"");
buffer.append(t);
// $NON-NLS-1$
buffer.append("\"");
} else {
buffer.append(t);
}
/* don't append separator _after_ last column */
if (j < columnCount - 1) {
buffer.append(columnSeparator);
}
}
writer.println(buffer.toString());
}
writer.close();
} catch (final Exception e) {
_table.getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(_table.getShell(), Messages.getString("SQLResultsView.Error.Export.Title"), e.getMessage());
}
});
}
}
});
}
Aggregations