From 3cef86029975579d4e05f4ca88ad63b22bff10f6 Mon Sep 17 00:00:00 2001 From: Eduardo Ramos Date: Fri, 7 Dec 2012 20:28:13 +0100 Subject: [PATCH] Fix Issue #628 : Spreadsheet export is now able to export hidden columns in data laboratory and is not affected by localization. --- .../datatables/AttributeTableCSVExporter.java | 135 +++++ .../merge/ui/CreateTimeIntervalUI.java | 5 +- .../columns/merge/ui/Bundle.properties | 46 +- .../datalab/DataTableTopComponent.java | 54 +- .../datalab/general/actions/CSVExportUI.form | 2 +- .../datalab/general/actions/CSVExportUI.java | 504 +++++++++--------- .../gephi/desktop/datalab/Bundle.properties | 5 + ...SVExporter.java => JTableCSVExporter.java} | 208 ++++---- .../org/gephi/utils/Bundle.properties | 6 +- 9 files changed, 567 insertions(+), 398 deletions(-) create mode 100644 modules/DataLaboratoryAPI/src/main/java/org/gephi/datalab/api/datatables/AttributeTableCSVExporter.java rename modules/Utils/src/main/java/org/gephi/utils/{TableCSVExporter.java => JTableCSVExporter.java} (96%) diff --git a/modules/DataLaboratoryAPI/src/main/java/org/gephi/datalab/api/datatables/AttributeTableCSVExporter.java b/modules/DataLaboratoryAPI/src/main/java/org/gephi/datalab/api/datatables/AttributeTableCSVExporter.java new file mode 100644 index 000000000..c66e51e65 --- /dev/null +++ b/modules/DataLaboratoryAPI/src/main/java/org/gephi/datalab/api/datatables/AttributeTableCSVExporter.java @@ -0,0 +1,135 @@ +/* + Copyright 2008-2010 Gephi + Authors : Eduardo Ramos + Website : http://www.gephi.org + + This file is part of Gephi. + + DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + + Copyright 2011 Gephi Consortium. All rights reserved. + + The contents of this file are subject to the terms of either the GNU + General Public License Version 3 only ("GPL") or the Common + Development and Distribution License("CDDL") (collectively, the + "License"). You may not use this file except in compliance with the + License. You can obtain a copy of the License at + http://gephi.org/about/legal/license-notice/ + or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the + specific language governing permissions and limitations under the + License. When distributing the software, include this License Header + Notice in each file and include the License files at + /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the + License Header, with the fields enclosed by brackets [] replaced by + your own identifying information: + "Portions Copyrighted [year] [name of copyright owner]" + + If you wish your version of this file to be governed by only the CDDL + or only the GPL Version 3, indicate your decision by adding + "[Contributor] elects to include this software in this distribution + under the [CDDL or GPL Version 3] license." If you do not indicate a + single choice of license, a recipient has the option to distribute + your version of this file under either the CDDL, the GPL Version 3 or + to extend the choice of license to its licensees as provided above. + However, if you add GPL Version 3 code and therefore, elected the GPL + Version 3 license, then the option applies only if the new code is + made subject to such option by the copyright holder. + + Contributor(s): + + Portions Copyrighted 2011 Gephi Consortium. + */ +package org.gephi.datalab.api.datatables; + +import com.csvreader.CsvWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.Charset; +import org.gephi.data.attributes.api.AttributeColumn; +import org.gephi.data.attributes.api.AttributeTable; +import org.gephi.graph.api.Attributable; +import org.gephi.graph.api.Edge; + +public class AttributeTableCSVExporter { + + private static final Character DEFAULT_SEPARATOR = ','; + public static final int FAKE_COLUMN_EDGE_SOURCE = -1; + public static final int FAKE_COLUMN_EDGE_TARGET = -2; + public static final int FAKE_COLUMN_EDGE_TYPE = -3; + + /** + *

Export a AttributeTable to the specified file.

+ * + * @param table Table to export + * @param file File to write + * @param separator Separator to use for separating values of a row in the CSV file. If null ',' will be used. + * @param charset Charset encoding for the file + * @param columnsToExport Indicates the indexes of the columns to export. All columns will be exported if null + * @throws IOException When an error happens while writing the file + */ + public static void writeCSVFile(AttributeTable table, File file, Character separator, Charset charset, Integer[] columnsToExport, Attributable[] rows) throws IOException { + FileOutputStream out = new FileOutputStream(file); + if (separator == null) { + separator = DEFAULT_SEPARATOR; + } + + AttributeColumn columns[] = table.getColumns(); + + if (columnsToExport == null) { + columnsToExport = new Integer[columns.length]; + for (int i = 0; i < columnsToExport.length; i++) { + columnsToExport[i] = columns[i].getIndex(); + } + } + + CsvWriter writer = new CsvWriter(out, separator, charset); + + + + //Write column headers: + for (int column = 0; column < columnsToExport.length; column++) { + int columnIndex = columnsToExport[column]; + + if (columnIndex == FAKE_COLUMN_EDGE_SOURCE) { + writer.write("Source"); + } else if (columnIndex == FAKE_COLUMN_EDGE_TARGET) { + writer.write("Target"); + } else if (columnIndex == FAKE_COLUMN_EDGE_TYPE) { + writer.write("Type"); + } else { + writer.write(table.getColumn(columnIndex).getTitle(), true); + } + + } + writer.endRecord(); + + //Write rows: + Object value; + String text; + for (int row = 0; row < rows.length; row++) { + for (int column = 0; column < columnsToExport.length; column++) { + int columnIndex = columnsToExport[column]; + + if (columnIndex == FAKE_COLUMN_EDGE_SOURCE) { + value = ((Edge)rows[row]).getSource().getNodeData().getId(); + } else if (columnIndex == FAKE_COLUMN_EDGE_TARGET) { + value = ((Edge)rows[row]).getTarget().getNodeData().getId(); + } else if (columnIndex == FAKE_COLUMN_EDGE_TYPE) { + value = ((Edge)rows[row]).isDirected() ? "Directed" : "Undirected"; + } else { + value = rows[row].getAttributes().getValue(columnIndex); + } + + if (value != null) { + text = value.toString(); + } else { + text = ""; + } + writer.write(text, true); + } + writer.endRecord(); + } + writer.close(); + } +} diff --git a/modules/DataLaboratoryPlugin/src/main/java/org/gephi/datalab/plugin/manipulators/columns/merge/ui/CreateTimeIntervalUI.java b/modules/DataLaboratoryPlugin/src/main/java/org/gephi/datalab/plugin/manipulators/columns/merge/ui/CreateTimeIntervalUI.java index 546f36097..8eaae3b45 100644 --- a/modules/DataLaboratoryPlugin/src/main/java/org/gephi/datalab/plugin/manipulators/columns/merge/ui/CreateTimeIntervalUI.java +++ b/modules/DataLaboratoryPlugin/src/main/java/org/gephi/datalab/plugin/manipulators/columns/merge/ui/CreateTimeIntervalUI.java @@ -57,6 +57,7 @@ import org.netbeans.validation.api.Problems; import org.netbeans.validation.api.Validator; import org.netbeans.validation.api.ui.ValidationGroup; import org.netbeans.validation.api.ui.ValidationPanel; +import org.openide.util.NbBundle; import org.openide.util.NbPreferences; /** @@ -204,7 +205,7 @@ public class CreateTimeIntervalUI extends javax.swing.JPanel implements Manipula public boolean validate(Problems prblms, String string, String t) { boolean valid = validateDateFormat(t); if(!valid){ - prblms.add("Invalid date format"); + prblms.add(NbBundle.getMessage(CreateTimeIntervalUI.class, "CreateTimeIntervalUI.invalid.dateformat")); } return valid; } @@ -215,7 +216,7 @@ public class CreateTimeIntervalUI extends javax.swing.JPanel implements Manipula public boolean validate(Problems prblms, String string, String t) { boolean valid = validateNumberOrEmpty(t); if(!valid){ - prblms.add("Invalid number"); + prblms.add(NbBundle.getMessage(CreateTimeIntervalUI.class, "CreateTimeIntervalUI.invalid.number")); } return valid; } diff --git a/modules/DataLaboratoryPlugin/src/main/resources/org/gephi/datalab/plugin/manipulators/columns/merge/ui/Bundle.properties b/modules/DataLaboratoryPlugin/src/main/resources/org/gephi/datalab/plugin/manipulators/columns/merge/ui/Bundle.properties index 43ec5b711..147a22bd1 100644 --- a/modules/DataLaboratoryPlugin/src/main/resources/org/gephi/datalab/plugin/manipulators/columns/merge/ui/Bundle.properties +++ b/modules/DataLaboratoryPlugin/src/main/resources/org/gephi/datalab/plugin/manipulators/columns/merge/ui/Bundle.properties @@ -1,22 +1,24 @@ -BooleanLogicOperationsUI.descriptionLabel.text=
Choose the logical operations between each pair of columns
-BooleanLogicOperationsUI.titleLabel.text=New column title: -JoinWithSeparatorUI.titleLabel.text=New column title: -JoinWithSeparatorUI.separatorLabel.text=Separator text: -JoinWithSeparatorUI.separatorText.text= -BooleanLogicOperationsUI.titleTextField.text= -JoinWithSeparatorUI.titleTextField.text= -GeneralColumnTitleChooserUI.titleLabel.text=New column title: -GeneralColumnTitleChooserUI.titleTextField.text= -CreateTimeIntervalUI.startColumnLabel.text=Start time column: -CreateTimeIntervalUI.endColumnLabel.text=End time column: -CreateTimeIntervalUI.header.title=Time Interval creation options -CreateTimeIntervalUI.header.description=Choose columns to use as start and/or end times.
Also you can choose default start and end times to use when values are not correct or missing, else infinity will be used instead. -CreateTimeIntervalUI.parseDatesRadioButton.text=Parse dates -CreateTimeIntervalUI.parseNumbersRadioButton.text=Parse numbers -CreateTimeIntervalUI.dateDefaultStartLabel.text=Default start time: -CreateTimeIntervalUI.dateDefaultEndLabel.text=Default end time: -CreateTimeIntervalUI.dateFormatLabel.text=Date format: -CreateTimeIntervalUI.defaultStartNumberText.text= -CreateTimeIntervalUI.defaultEndNumberText.text= -CreateTimeIntervalUI.defaultStartNumberLabel.text=Default start time: -CreateTimeIntervalUI.defaultEndNumberLabel.text=Default end time: +BooleanLogicOperationsUI.descriptionLabel.text=
Choose the logical operations between each pair of columns
+BooleanLogicOperationsUI.titleLabel.text=New column title: +JoinWithSeparatorUI.titleLabel.text=New column title: +JoinWithSeparatorUI.separatorLabel.text=Separator text: +JoinWithSeparatorUI.separatorText.text= +BooleanLogicOperationsUI.titleTextField.text= +JoinWithSeparatorUI.titleTextField.text= +GeneralColumnTitleChooserUI.titleLabel.text=New column title: +GeneralColumnTitleChooserUI.titleTextField.text= +CreateTimeIntervalUI.startColumnLabel.text=Start time column: +CreateTimeIntervalUI.endColumnLabel.text=End time column: +CreateTimeIntervalUI.header.title=Time Interval creation options +CreateTimeIntervalUI.header.description=Choose columns to use as start and/or end times.
Also you can choose default start and end times to use when values are not correct or missing, else infinity will be used instead. +CreateTimeIntervalUI.parseDatesRadioButton.text=Parse dates +CreateTimeIntervalUI.parseNumbersRadioButton.text=Parse numbers +CreateTimeIntervalUI.dateDefaultStartLabel.text=Default start time: +CreateTimeIntervalUI.dateDefaultEndLabel.text=Default end time: +CreateTimeIntervalUI.dateFormatLabel.text=Date format: +CreateTimeIntervalUI.defaultStartNumberText.text= +CreateTimeIntervalUI.defaultEndNumberText.text= +CreateTimeIntervalUI.defaultStartNumberLabel.text=Default start time: +CreateTimeIntervalUI.defaultEndNumberLabel.text=Default end time: +CreateTimeIntervalUI.invalid.dateformat=Invalid date format +CreateTimeIntervalUI.invalid.number=Invalid number diff --git a/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/DataTableTopComponent.java b/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/DataTableTopComponent.java index 44b0a7674..cb3c2540d 100644 --- a/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/DataTableTopComponent.java +++ b/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/DataTableTopComponent.java @@ -49,7 +49,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; -import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; @@ -60,6 +59,7 @@ import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.gephi.data.attributes.api.*; import org.gephi.datalab.api.DataLaboratoryHelper; +import org.gephi.datalab.api.datatables.AttributeTableCSVExporter; import org.gephi.datalab.api.datatables.DataTablesController; import org.gephi.datalab.api.datatables.DataTablesEventListener; import org.gephi.datalab.spi.ContextMenuItemManipulator; @@ -73,11 +73,11 @@ import org.gephi.desktop.datalab.general.actions.CSVExportUI; import org.gephi.desktop.datalab.general.actions.MergeColumnsUI; import org.gephi.graph.api.*; import org.gephi.project.api.*; -import org.gephi.ui.components.WrapLayout; import org.gephi.ui.components.BusyUtils; +import org.gephi.ui.components.WrapLayout; import org.gephi.ui.utils.DialogFileFilter; import org.gephi.ui.utils.UIUtils; -import org.gephi.utils.TableCSVExporter; +import org.gephi.utils.JTableCSVExporter; import org.netbeans.api.settings.ConvertAsProperties; import org.netbeans.swing.etable.ETableColumnModel; import org.openide.DialogDescriptor; @@ -697,21 +697,25 @@ public class DataTableTopComponent extends TopComponent implements AWTEventListe } public void exportCurrentTable(ExportMode exportMode) { - JTable table; + AttributeTable table; + Attributes[] rows; String fileName = prepareTableExportFileName(); + boolean edgesTable; if (classDisplayed == ClassDisplayed.NODE) { - table = nodeTable.getOutlineTable(); + table = Lookup.getDefault().lookup(AttributeController.class).getModel().getNodeTable(); + edgesTable = false; fileName += " [Nodes]"; } else { - table = edgeTable.getTable(); + table = Lookup.getDefault().lookup(AttributeController.class).getModel().getEdgeTable(); + edgesTable = true; fileName += " [Edges]"; } fileName += ".csv"; switch (exportMode) { case CSV: - showCSVExportUI(table, fileName); + showCSVExportUI(table, edgesTable, fileName); break; } } @@ -750,11 +754,11 @@ public class DataTableTopComponent extends TopComponent implements AWTEventListe return fileName; } - private void showCSVExportUI(JTable table, String fileName) { - CSVExportUI csvUI = new CSVExportUI(table); + private void showCSVExportUI(AttributeTable table, boolean edgesTable, String fileName) { + CSVExportUI csvUI = new CSVExportUI(table, edgesTable); DialogDescriptor dd = new DialogDescriptor(csvUI, csvUI.getDisplayName()); if (DialogDisplayer.getDefault().notify(dd).equals(DialogDescriptor.OK_OPTION)) { - DataTableTopComponent.exportTableAsCSV(this, table, csvUI.getSelectedSeparator(), csvUI.getSelectedCharset(), csvUI.getSelectedColumnsIndexes(), fileName); + DataTableTopComponent.exportTableAsCSV(this, table, edgesTable, csvUI.getSelectedSeparator(), csvUI.getSelectedCharset(), csvUI.getSelectedColumnsIndexes(), fileName); } csvUI.unSetup(); } @@ -1411,7 +1415,7 @@ public class DataTableTopComponent extends TopComponent implements AWTEventListe } /** - *

Exports a JTable to a CSV file showing first a dialog to select the + *

Exports a AttributeTable to a CSV file showing first a dialog to select the * file to write.

* * @param parent Parent window @@ -1422,11 +1426,16 @@ public class DataTableTopComponent extends TopComponent implements AWTEventListe * @param columnsToExport Indicates the indexes of the columns to export. * All columns will be exported if null */ - public static void exportTableAsCSV(JComponent parent, JTable table, Character separator, Charset charset, Integer[] columnsToExport, String fileName) { - String lastPath = NbPreferences.forModule(TableCSVExporter.class).get(LAST_PATH, null); + public static void exportTableAsCSV(JComponent parent, AttributeTable table, boolean edgesTable, Character separator, Charset charset, Integer[] columnsToExport, String fileName) { + //Validate that at least 1 column is selected: + if(columnsToExport.length < 1){ + return; + } + + String lastPath = NbPreferences.forModule(JTableCSVExporter.class).get(LAST_PATH, null); final JFileChooser chooser = new JFileChooser(lastPath); chooser.setAcceptAllFileFilterUsed(false); - DialogFileFilter dialogFileFilter = new DialogFileFilter(NbBundle.getMessage(TableCSVExporter.class, "TableCSVExporter.filechooser.csvDescription")); + DialogFileFilter dialogFileFilter = new DialogFileFilter(NbBundle.getMessage(DataTableTopComponent.class, "TableCSVExporter.filechooser.csvDescription")); dialogFileFilter.addExtension("csv"); chooser.addChoosableFileFilter(dialogFileFilter); File selectedFile = new File(chooser.getCurrentDirectory(), fileName); @@ -1443,12 +1452,19 @@ public class DataTableTopComponent extends TopComponent implements AWTEventListe //Save last path String defaultDirectory = file.getParentFile().getAbsolutePath(); - NbPreferences.forModule(TableCSVExporter.class).put(LAST_PATH, defaultDirectory); + NbPreferences.forModule(JTableCSVExporter.class).put(LAST_PATH, defaultDirectory); try { - TableCSVExporter.writeCSVFile(table, file, separator, charset, columnsToExport); - JOptionPane.showMessageDialog(parent, NbBundle.getMessage(TableCSVExporter.class, "TableCSVExporter.dialog.success")); - } catch (IOException ex) { - JOptionPane.showMessageDialog(parent, NbBundle.getMessage(TableCSVExporter.class, "TableCSVExporter.dialog.error"), NbBundle.getMessage(TableCSVExporter.class, "TableCSVExporter.dialog.error.title"), JOptionPane.ERROR_MESSAGE); + Attributable[] rows; + if(edgesTable){ + rows = Lookup.getDefault().lookup(GraphController.class).getModel().getGraph().getEdges().toArray(); + }else{ + rows = Lookup.getDefault().lookup(GraphController.class).getModel().getGraph().getNodes().toArray(); + } + + AttributeTableCSVExporter.writeCSVFile(table, file, separator, charset, columnsToExport, rows); + JOptionPane.showMessageDialog(parent, NbBundle.getMessage(DataTableTopComponent.class, "TableCSVExporter.dialog.success")); + } catch (Exception ex) { + JOptionPane.showMessageDialog(parent, NbBundle.getMessage(DataTableTopComponent.class, "TableCSVExporter.dialog.error"), NbBundle.getMessage(DataTableTopComponent.class, "TableCSVExporter.dialog.error.title"), JOptionPane.ERROR_MESSAGE); } } private static final String LAST_PATH = "TableCSVExporter_Save_Last_Path"; diff --git a/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.form b/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.form index 2a76d7891..b2dae56e3 100644 --- a/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.form +++ b/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.form @@ -1,4 +1,4 @@ - +
diff --git a/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.java b/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.java index c3bb274d7..a5022a86d 100644 --- a/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.java +++ b/modules/DesktopDataLaboratory/src/main/java/org/gephi/desktop/datalab/general/actions/CSVExportUI.java @@ -1,245 +1,259 @@ -/* -Copyright 2008-2010 Gephi -Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke, Eduardo Ramos -Website : http://www.gephi.org - -This file is part of Gephi. - -DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - -Copyright 2011 Gephi Consortium. All rights reserved. - -The contents of this file are subject to the terms of either the GNU -General Public License Version 3 only ("GPL") or the Common -Development and Distribution License("CDDL") (collectively, the -"License"). You may not use this file except in compliance with the -License. You can obtain a copy of the License at -http://gephi.org/about/legal/license-notice/ -or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the -specific language governing permissions and limitations under the -License. When distributing the software, include this License Header -Notice in each file and include the License files at -/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the -License Header, with the fields enclosed by brackets [] replaced by -your own identifying information: -"Portions Copyrighted [year] [name of copyright owner]" - -If you wish your version of this file to be governed by only the CDDL -or only the GPL Version 3, indicate your decision by adding -"[Contributor] elects to include this software in this distribution -under the [CDDL or GPL Version 3] license." If you do not indicate a -single choice of license, a recipient has the option to distribute -your version of this file under either the CDDL, the GPL Version 3 or -to extend the choice of license to its licensees as provided above. -However, if you add GPL Version 3 code and therefore, elected the GPL -Version 3 license, then the option applies only if the new code is -made subject to such option by the copyright holder. - -Contributor(s): - -Portions Copyrighted 2011 Gephi Consortium. -*/ -package org.gephi.desktop.datalab.general.actions; - -import java.nio.charset.Charset; -import java.util.ArrayList; -import javax.swing.JCheckBox; -import javax.swing.JTable; -import javax.swing.table.TableModel; -import net.miginfocom.swing.MigLayout; -import org.netbeans.swing.outline.Outline; -import org.openide.util.NbBundle; -import org.openide.util.NbPreferences; - -/** - * UI for selecting CSV export options of a JTable. - * @author Eduardo Ramos - */ -public class CSVExportUI extends javax.swing.JPanel { - - private static final String CHARSET_SAVED_PREFERENCES = "CSVExportUI_Charset"; - private static final String SEPARATOR_SAVED_PREFERENCES = "CSVExportUI_Separator"; - private JTable table; - private JCheckBox[] columnsCheckBoxes; - - /** Creates new form CSVExportUI */ - public CSVExportUI(JTable table) { - initComponents(); - this.table = table; - separatorComboBox.addItem(new SeparatorWrapper((','), getMessage("CSVExportUI.comma"))); - separatorComboBox.addItem(new SeparatorWrapper((';'), getMessage("CSVExportUI.semicolon"))); - separatorComboBox.addItem(new SeparatorWrapper(('\t'), getMessage("CSVExportUI.tab"))); - separatorComboBox.addItem(new SeparatorWrapper((' '), getMessage("CSVExportUI.space"))); - - separatorComboBox.setSelectedIndex(NbPreferences.forModule(CSVExportUI.class).getInt(SEPARATOR_SAVED_PREFERENCES, 0));//Use saved separator or comma if not saved - - for (String charset : Charset.availableCharsets().keySet()) { - charsetComboBox.addItem(charset); - } - String savedCharset = NbPreferences.forModule(CSVExportUI.class).get(CHARSET_SAVED_PREFERENCES, null); - if (savedCharset != null) { - charsetComboBox.setSelectedItem(savedCharset); - }else{ - charsetComboBox.setSelectedItem(Charset.forName("UTF-8").name());//UTF-8 by default, not system default charset - } - refreshColumns(); - } - - public void unSetup(){ - NbPreferences.forModule(CSVExportUI.class).put(CHARSET_SAVED_PREFERENCES, charsetComboBox.getSelectedItem().toString()); - NbPreferences.forModule(CSVExportUI.class).putInt(SEPARATOR_SAVED_PREFERENCES, separatorComboBox.getSelectedIndex()); - } - - private void refreshColumns() { - boolean outlineTable = table instanceof Outline; - TableModel model = table.getModel(); - columnsCheckBoxes = new JCheckBox[model.getColumnCount()]; - columnsPanel.removeAll(); - columnsPanel.setLayout(new MigLayout("", "[pref!]")); - - - int modelIndex; - //Show rest of columns: - for (int i = 0; i < table.getColumnCount(); i++) { - modelIndex=table.convertColumnIndexToModel(i); - if(modelIndex==0){ - if(outlineTable){//If outline table, hide nodes tree column from exporting (first column) - columnsCheckBoxes[i] = new JCheckBox(model.getColumnName(modelIndex), false); - continue; - } - } - columnsCheckBoxes[i] = new JCheckBox(model.getColumnName(modelIndex), true); - columnsPanel.add(columnsCheckBoxes[i], "wrap"); - } - columnsPanel.revalidate(); - columnsPanel.repaint(); - } - - public String getDisplayName() { - return getMessage("CSVExportUI.title"); - } - - public Character getSelectedSeparator() { - Object item = separatorComboBox.getSelectedItem(); - if (item instanceof SeparatorWrapper) { - return ((SeparatorWrapper) item).separator; - } else { - return item.toString().charAt(0); - } - } - - public Integer[] getSelectedColumnsIndexes() { - ArrayList columnsIndexes = new ArrayList(); - for (int i = 0; i < columnsCheckBoxes.length; i++) { - if (columnsCheckBoxes[i].isSelected()) { - columnsIndexes.add(table.convertColumnIndexToModel(i)); - } - } - return columnsIndexes.toArray(new Integer[0]); - } - - public Charset getSelectedCharset() { - return Charset.forName(charsetComboBox.getSelectedItem().toString()); - } - - class SeparatorWrapper { - - private Character separator; - private String displayText; - - public SeparatorWrapper(Character separator) { - this.separator = separator; - } - - public SeparatorWrapper(Character separator, String displayText) { - this.separator = separator; - this.displayText = displayText; - } - - @Override - public String toString() { - if (displayText != null) { - return displayText; - } else { - return String.valueOf(separator); - } - } - } - - private String getMessage(String resName) { - return NbBundle.getMessage(CSVExportUI.class, resName); - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - @SuppressWarnings("unchecked") - // //GEN-BEGIN:initComponents - private void initComponents() { - - separatorLabel = new javax.swing.JLabel(); - separatorComboBox = new javax.swing.JComboBox(); - scroll = new javax.swing.JScrollPane(); - columnsPanel = new javax.swing.JPanel(); - columnsLabel = new javax.swing.JLabel(); - charsetLabel = new javax.swing.JLabel(); - charsetComboBox = new javax.swing.JComboBox(); - - separatorLabel.setText(org.openide.util.NbBundle.getMessage(CSVExportUI.class, "CSVExportUI.separatorLabel.text")); // NOI18N - - columnsPanel.setLayout(new java.awt.GridLayout(1, 0)); - scroll.setViewportView(columnsPanel); - - columnsLabel.setText(org.openide.util.NbBundle.getMessage(CSVExportUI.class, "CSVExportUI.columnsLabel.text")); // NOI18N - - charsetLabel.setText(org.openide.util.NbBundle.getMessage(CSVExportUI.class, "CSVExportUI.charsetLabel.text")); // NOI18N - - javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); - this.setLayout(layout); - layout.setHorizontalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addContainerGap() - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addComponent(separatorLabel) - .addGap(18, 18, 18) - .addComponent(separatorComboBox, 0, 150, Short.MAX_VALUE)) - .addComponent(columnsLabel) - .addGroup(layout.createSequentialGroup() - .addComponent(charsetLabel) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(charsetComboBox, 0, 174, Short.MAX_VALUE))) - .addContainerGap()) - ); - layout.setVerticalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(layout.createSequentialGroup() - .addContainerGap() - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(separatorLabel) - .addComponent(separatorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(charsetLabel) - .addComponent(charsetComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(columnsLabel) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE) - .addContainerGap()) - ); - }// //GEN-END:initComponents - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JComboBox charsetComboBox; - private javax.swing.JLabel charsetLabel; - private javax.swing.JLabel columnsLabel; - private javax.swing.JPanel columnsPanel; - private javax.swing.JScrollPane scroll; - private javax.swing.JComboBox separatorComboBox; - private javax.swing.JLabel separatorLabel; - // End of variables declaration//GEN-END:variables -} +/* + Copyright 2008-2010 Gephi + Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke, Eduardo Ramos + Website : http://www.gephi.org + + This file is part of Gephi. + + DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + + Copyright 2011 Gephi Consortium. All rights reserved. + + The contents of this file are subject to the terms of either the GNU + General Public License Version 3 only ("GPL") or the Common + Development and Distribution License("CDDL") (collectively, the + "License"). You may not use this file except in compliance with the + License. You can obtain a copy of the License at + http://gephi.org/about/legal/license-notice/ + or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the + specific language governing permissions and limitations under the + License. When distributing the software, include this License Header + Notice in each file and include the License files at + /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the + License Header, with the fields enclosed by brackets [] replaced by + your own identifying information: + "Portions Copyrighted [year] [name of copyright owner]" + + If you wish your version of this file to be governed by only the CDDL + or only the GPL Version 3, indicate your decision by adding + "[Contributor] elects to include this software in this distribution + under the [CDDL or GPL Version 3] license." If you do not indicate a + single choice of license, a recipient has the option to distribute + your version of this file under either the CDDL, the GPL Version 3 or + to extend the choice of license to its licensees as provided above. + However, if you add GPL Version 3 code and therefore, elected the GPL + Version 3 license, then the option applies only if the new code is + made subject to such option by the copyright holder. + + Contributor(s): + + Portions Copyrighted 2011 Gephi Consortium. + */ +package org.gephi.desktop.datalab.general.actions; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import javax.swing.JCheckBox; +import net.miginfocom.swing.MigLayout; +import org.gephi.data.attributes.api.AttributeColumn; +import org.gephi.data.attributes.api.AttributeTable; +import org.gephi.datalab.api.datatables.AttributeTableCSVExporter; +import org.openide.util.NbBundle; +import org.openide.util.NbPreferences; + +/** + * UI for selecting CSV export options of a JTable. + * + * @author Eduardo Ramos + */ +public class CSVExportUI extends javax.swing.JPanel { + + private static final String CHARSET_SAVED_PREFERENCES = "CSVExportUI_Charset"; + private static final String SEPARATOR_SAVED_PREFERENCES = "CSVExportUI_Separator"; + private final AttributeColumn[] columns; + private ColumnCheckboxWrapper[] columnsCheckBoxes; + private final boolean edgesTable; + + /** + * Creates new form CSVExportUI + */ + public CSVExportUI(AttributeTable table, boolean edgesTable) { + initComponents(); + this.columns = table.getColumns(); + this.edgesTable = edgesTable; + separatorComboBox.addItem(new SeparatorWrapper((','), getMessage("CSVExportUI.comma"))); + separatorComboBox.addItem(new SeparatorWrapper((';'), getMessage("CSVExportUI.semicolon"))); + separatorComboBox.addItem(new SeparatorWrapper(('\t'), getMessage("CSVExportUI.tab"))); + separatorComboBox.addItem(new SeparatorWrapper((' '), getMessage("CSVExportUI.space"))); + + separatorComboBox.setSelectedIndex(NbPreferences.forModule(CSVExportUI.class).getInt(SEPARATOR_SAVED_PREFERENCES, 0));//Use saved separator or comma if not saved + + for (String charset : Charset.availableCharsets().keySet()) { + charsetComboBox.addItem(charset); + } + String savedCharset = NbPreferences.forModule(CSVExportUI.class).get(CHARSET_SAVED_PREFERENCES, null); + if (savedCharset != null) { + charsetComboBox.setSelectedItem(savedCharset); + } else { + charsetComboBox.setSelectedItem(Charset.forName("UTF-8").name());//UTF-8 by default, not system default charset + } + refreshColumns(); + } + + public void unSetup() { + NbPreferences.forModule(CSVExportUI.class).put(CHARSET_SAVED_PREFERENCES, charsetComboBox.getSelectedItem().toString()); + NbPreferences.forModule(CSVExportUI.class).putInt(SEPARATOR_SAVED_PREFERENCES, separatorComboBox.getSelectedIndex()); + } + + private void refreshColumns() { + columnsPanel.removeAll(); + columnsPanel.setLayout(new MigLayout("", "[pref!]")); + + ArrayList columnCheckboxesList = new ArrayList(); + + //In case of edges table, we need to include fake source, target and type columns: + if(edgesTable){ + columnCheckboxesList.add(new ColumnCheckboxWrapper(AttributeTableCSVExporter.FAKE_COLUMN_EDGE_SOURCE, "Source", true)); + columnCheckboxesList.add(new ColumnCheckboxWrapper(AttributeTableCSVExporter.FAKE_COLUMN_EDGE_TARGET, "Target", true)); + columnCheckboxesList.add(new ColumnCheckboxWrapper(AttributeTableCSVExporter.FAKE_COLUMN_EDGE_TYPE, "Type", true)); + } + + //Show rest of columns: + for (AttributeColumn column : columns) { + columnCheckboxesList.add(new ColumnCheckboxWrapper(column.getIndex(), column.getTitle(), true)); + } + + columnsCheckBoxes = columnCheckboxesList.toArray(new ColumnCheckboxWrapper[0]); + for (ColumnCheckboxWrapper columnCheckboxWrapper : columnsCheckBoxes) { + columnsPanel.add(columnCheckboxWrapper, "wrap"); + } + + columnsPanel.revalidate(); + columnsPanel.repaint(); + } + + public String getDisplayName() { + return getMessage("CSVExportUI.title"); + } + + public Character getSelectedSeparator() { + Object item = separatorComboBox.getSelectedItem(); + if (item instanceof SeparatorWrapper) { + return ((SeparatorWrapper) item).separator; + } else { + return item.toString().charAt(0); + } + } + + public Integer[] getSelectedColumnsIndexes() { + ArrayList columnsIndexes = new ArrayList(); + for (int i = 0; i < columnsCheckBoxes.length; i++) { + if (columnsCheckBoxes[i].isSelected()) { + columnsIndexes.add(columnsCheckBoxes[i].index); + } + } + return columnsIndexes.toArray(new Integer[0]); + } + + public Charset getSelectedCharset() { + return Charset.forName(charsetComboBox.getSelectedItem().toString()); + } + + class SeparatorWrapper { + + private Character separator; + private String displayText; + + public SeparatorWrapper(Character separator) { + this.separator = separator; + } + + public SeparatorWrapper(Character separator, String displayText) { + this.separator = separator; + this.displayText = displayText; + } + + @Override + public String toString() { + if (displayText != null) { + return displayText; + } else { + return String.valueOf(separator); + } + } + } + + private String getMessage(String resName) { + return NbBundle.getMessage(CSVExportUI.class, resName); + } + + class ColumnCheckboxWrapper extends JCheckBox{ + int index; + + public ColumnCheckboxWrapper(int index, String text, boolean selected) { + super(text, selected); + this.index = index; + } + } + + /** + * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + separatorLabel = new javax.swing.JLabel(); + separatorComboBox = new javax.swing.JComboBox(); + scroll = new javax.swing.JScrollPane(); + columnsPanel = new javax.swing.JPanel(); + columnsLabel = new javax.swing.JLabel(); + charsetLabel = new javax.swing.JLabel(); + charsetComboBox = new javax.swing.JComboBox(); + + separatorLabel.setText(org.openide.util.NbBundle.getMessage(CSVExportUI.class, "CSVExportUI.separatorLabel.text")); // NOI18N + + columnsPanel.setLayout(new java.awt.GridLayout(1, 0)); + scroll.setViewportView(columnsPanel); + + columnsLabel.setText(org.openide.util.NbBundle.getMessage(CSVExportUI.class, "CSVExportUI.columnsLabel.text")); // NOI18N + + charsetLabel.setText(org.openide.util.NbBundle.getMessage(CSVExportUI.class, "CSVExportUI.charsetLabel.text")); // NOI18N + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(separatorLabel) + .addGap(18, 18, 18) + .addComponent(separatorComboBox, 0, 150, Short.MAX_VALUE)) + .addComponent(columnsLabel) + .addGroup(layout.createSequentialGroup() + .addComponent(charsetLabel) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(charsetComboBox, 0, 174, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(separatorLabel) + .addComponent(separatorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(charsetLabel) + .addComponent(charsetComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(columnsLabel) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE) + .addContainerGap()) + ); + }// //GEN-END:initComponents + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JComboBox charsetComboBox; + private javax.swing.JLabel charsetLabel; + private javax.swing.JLabel columnsLabel; + private javax.swing.JPanel columnsPanel; + private javax.swing.JScrollPane scroll; + private javax.swing.JComboBox separatorComboBox; + private javax.swing.JLabel separatorLabel; + // End of variables declaration//GEN-END:variables +} diff --git a/modules/DesktopDataLaboratory/src/main/resources/org/gephi/desktop/datalab/Bundle.properties b/modules/DesktopDataLaboratory/src/main/resources/org/gephi/desktop/datalab/Bundle.properties index 466400203..c7f338e5f 100644 --- a/modules/DesktopDataLaboratory/src/main/resources/org/gephi/desktop/datalab/Bundle.properties +++ b/modules/DesktopDataLaboratory/src/main/resources/org/gephi/desktop/datalab/Bundle.properties @@ -46,3 +46,8 @@ AvailableColumnsPanel.title=Display settings AvailableColumnsPanel.descriptionLabel.text=Choose the columns to display: AvailableColumnsPanel.maximum-available-columns.info=Maximum number of columns reached ConfigurationPanel.timeIntervalsAsDates.text=Time intervals as dates + +TableCSVExporter.dialog.success=Table exported with success +TableCSVExporter.dialog.error=An error happened when writing the file. Make sure the file is not in use and you have permissions +TableCSVExporter.dialog.error.title=Error +TableCSVExporter.filechooser.csvDescription=CSV \ No newline at end of file diff --git a/modules/Utils/src/main/java/org/gephi/utils/TableCSVExporter.java b/modules/Utils/src/main/java/org/gephi/utils/JTableCSVExporter.java similarity index 96% rename from modules/Utils/src/main/java/org/gephi/utils/TableCSVExporter.java rename to modules/Utils/src/main/java/org/gephi/utils/JTableCSVExporter.java index 096b5403e..6a2a8c195 100644 --- a/modules/Utils/src/main/java/org/gephi/utils/TableCSVExporter.java +++ b/modules/Utils/src/main/java/org/gephi/utils/JTableCSVExporter.java @@ -1,104 +1,104 @@ -/* -Copyright 2008-2010 Gephi -Authors : Eduardo Ramos -Website : http://www.gephi.org - -This file is part of Gephi. - -DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - -Copyright 2011 Gephi Consortium. All rights reserved. - -The contents of this file are subject to the terms of either the GNU -General Public License Version 3 only ("GPL") or the Common -Development and Distribution License("CDDL") (collectively, the -"License"). You may not use this file except in compliance with the -License. You can obtain a copy of the License at -http://gephi.org/about/legal/license-notice/ -or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the -specific language governing permissions and limitations under the -License. When distributing the software, include this License Header -Notice in each file and include the License files at -/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the -License Header, with the fields enclosed by brackets [] replaced by -your own identifying information: -"Portions Copyrighted [year] [name of copyright owner]" - -If you wish your version of this file to be governed by only the CDDL -or only the GPL Version 3, indicate your decision by adding -"[Contributor] elects to include this software in this distribution -under the [CDDL or GPL Version 3] license." If you do not indicate a -single choice of license, a recipient has the option to distribute -your version of this file under either the CDDL, the GPL Version 3 or -to extend the choice of license to its licensees as provided above. -However, if you add GPL Version 3 code and therefore, elected the GPL -Version 3 license, then the option applies only if the new code is -made subject to such option by the copyright holder. - -Contributor(s): - -Portions Copyrighted 2011 Gephi Consortium. - */ -package org.gephi.utils; - -import com.csvreader.CsvWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.charset.Charset; -import javax.swing.JTable; -import javax.swing.table.TableModel; - -public class TableCSVExporter { - - private static final Character DEFAULT_SEPARATOR = ','; - - /** - *

Export a JTable to the specified file.

- * @param table Table to export - * @param file File to write - * @param separator Separator to use for separating values of a row in the CSV file. If null ',' will be used. - * @param charset Charset encoding for the file - * @param columnsToExport Indicates the indexes of the columns to export. All columns will be exported if null - * @throws IOException When an error happens while writing the file - */ - public static void writeCSVFile(JTable table, File file, Character separator, Charset charset, Integer[] columnsToExport) throws IOException { - TableModel model = table.getModel(); - FileOutputStream out = new FileOutputStream(file); - if (separator == null) { - separator = DEFAULT_SEPARATOR; - } - - if (columnsToExport == null) { - columnsToExport = new Integer[model.getColumnCount()]; - for (int i = 0; i < columnsToExport.length; i++) { - columnsToExport[i] = i; - } - } - - CsvWriter writer = new CsvWriter(out, separator, charset); - - //Write column headers: - for (int column = 0; column < columnsToExport.length; column++) { - writer.write(model.getColumnName(columnsToExport[column]), true); - } - writer.endRecord(); - - //Write rows: - Object value; - String text; - for (int row = 0; row < table.getRowCount(); row++) { - for (int column = 0; column < columnsToExport.length; column++) { - value = model.getValueAt(table.convertRowIndexToModel(row), columnsToExport[column]); - if (value != null) { - text = value.toString(); - } else { - text = ""; - } - writer.write(text, true); - } - writer.endRecord(); - } - writer.close(); - } -} +/* +Copyright 2008-2010 Gephi +Authors : Eduardo Ramos +Website : http://www.gephi.org + +This file is part of Gephi. + +DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + +Copyright 2011 Gephi Consortium. All rights reserved. + +The contents of this file are subject to the terms of either the GNU +General Public License Version 3 only ("GPL") or the Common +Development and Distribution License("CDDL") (collectively, the +"License"). You may not use this file except in compliance with the +License. You can obtain a copy of the License at +http://gephi.org/about/legal/license-notice/ +or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the +specific language governing permissions and limitations under the +License. When distributing the software, include this License Header +Notice in each file and include the License files at +/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the +License Header, with the fields enclosed by brackets [] replaced by +your own identifying information: +"Portions Copyrighted [year] [name of copyright owner]" + +If you wish your version of this file to be governed by only the CDDL +or only the GPL Version 3, indicate your decision by adding +"[Contributor] elects to include this software in this distribution +under the [CDDL or GPL Version 3] license." If you do not indicate a +single choice of license, a recipient has the option to distribute +your version of this file under either the CDDL, the GPL Version 3 or +to extend the choice of license to its licensees as provided above. +However, if you add GPL Version 3 code and therefore, elected the GPL +Version 3 license, then the option applies only if the new code is +made subject to such option by the copyright holder. + +Contributor(s): + +Portions Copyrighted 2011 Gephi Consortium. + */ +package org.gephi.utils; + +import com.csvreader.CsvWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.Charset; +import javax.swing.JTable; +import javax.swing.table.TableModel; + +public class JTableCSVExporter { + + private static final Character DEFAULT_SEPARATOR = ','; + + /** + *

Export a JTable to the specified file.

+ * @param table Table to export + * @param file File to write + * @param separator Separator to use for separating values of a row in the CSV file. If null ',' will be used. + * @param charset Charset encoding for the file + * @param columnsToExport Indicates the indexes of the columns to export. All columns will be exported if null + * @throws IOException When an error happens while writing the file + */ + public static void writeCSVFile(JTable table, File file, Character separator, Charset charset, Integer[] columnsToExport) throws IOException { + TableModel model = table.getModel(); + FileOutputStream out = new FileOutputStream(file); + if (separator == null) { + separator = DEFAULT_SEPARATOR; + } + + if (columnsToExport == null) { + columnsToExport = new Integer[model.getColumnCount()]; + for (int i = 0; i < columnsToExport.length; i++) { + columnsToExport[i] = i; + } + } + + CsvWriter writer = new CsvWriter(out, separator, charset); + + //Write column headers: + for (int column = 0; column < columnsToExport.length; column++) { + writer.write(model.getColumnName(columnsToExport[column]), true); + } + writer.endRecord(); + + //Write rows: + Object value; + String text; + for (int row = 0; row < table.getRowCount(); row++) { + for (int column = 0; column < columnsToExport.length; column++) { + value = model.getValueAt(table.convertRowIndexToModel(row), columnsToExport[column]); + if (value != null) { + text = value.toString(); + } else { + text = ""; + } + writer.write(text, true); + } + writer.endRecord(); + } + writer.close(); + } +} diff --git a/modules/Utils/src/main/resources/org/gephi/utils/Bundle.properties b/modules/Utils/src/main/resources/org/gephi/utils/Bundle.properties index 77f1b321d..a94a5aa55 100644 --- a/modules/Utils/src/main/resources/org/gephi/utils/Bundle.properties +++ b/modules/Utils/src/main/resources/org/gephi/utils/Bundle.properties @@ -2,8 +2,4 @@ OpenIDE-Module-Display-Category=Gephi Core OpenIDE-Module-Long-Description=\ Utils classes for core OpenIDE-Module-Name=Utils -OpenIDE-Module-Short-Description=Utils classes for core -TableCSVExporter.dialog.success=Table exported with success -TableCSVExporter.dialog.error=An error happened when writing the file. Make sure the file is not in use and you have permissions -TableCSVExporter.dialog.error.title=Error -TableCSVExporter.filechooser.csvDescription=CSV \ No newline at end of file +OpenIDE-Module-Short-Description=Utils classes for core \ No newline at end of file -- GitLab