Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Class to create a JavaFX TableView from a CSV file
package com.jfxdev.controls;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public final class CSVTableView extends TableView<String> {
public CSVTableView(String delimiter, File file) throws IOException {
// Get CSV file lines as List
List<String> lines = Files.readAllLines(Paths.get(file.toURI()));
// Get the header row
String[] firstRow = lines.get(0).split(delimiter);
// For each header/column, create TableColumn
for (String columnName : firstRow) {
TableColumn<String, String> column = new TableColumn<>(columnName);
this.getColumns().add(column);
column.setCellValueFactory(cellDataFeatures -> {
String values = cellDataFeatures.getValue();
String[] cells = values.split(delimiter);
int columnIndex = cellDataFeatures.getTableView().getColumns().indexOf(cellDataFeatures.getTableColumn());
if (columnIndex >= cells.length) {
return new SimpleStringProperty("");
} else {
return new SimpleStringProperty(cells[columnIndex]);
}
});
this.setItems(FXCollections.observableArrayList(lines));
// Remove header row, as it will be added to the data at this point
// this only works if we're sure that our CSV file has a header,
// otherwise, we're just deleting data at this point.
this.getItems().remove(0);
}
}
}
@Aladdine95
Copy link

Aladdine95 commented Mar 16, 2022

Perfect match for me. Thanks a lot !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment