Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Class to create a JavaFX TableView from a CSV file
package com.jfxdev.controls;
import javafx.collections.FXCollections;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
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);
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]);
// 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.
Copy link

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