I’m seeking help on Vaadin Flow DataGrid, my question is how do I create a data grid from a csv file along with headers which are available in csv, where user can upload any csv and it must create the data grid populate the csv data dynamically. I could not found a help on this…I can’t define properties in pojo class cause I’ll not be knowing the column names until user upload the csv file…Any help related to this highly appreciated .
I’m seeking help on Vaadin Flow DataGrid, my question is how do I create a data grid from a csv file along with headers which are available in csv, where user can upload any csv and it must create the data grid populate the csv data dynamically. I could not found a help on this…I can’t define properties in pojo class cause I’ll not be knowing the column names until user upload the csv file…Any help related to this highly appreciated .
Cheers,
I went through the document and source code and found that grid.addColumn() method require attribute to be checked from bean class, where in my case i can’t define bean class while creating grid as i need to add columns and rows dynamically.
I wrote an example how to do this. This uses a custom version of Upload (UploadFileHandler) from Flow Viritin add-on, but the approach should be appliable also with raw Upload component. First line is expected to contain header row.
Grid<String[]> grid = new Grid<>();
UploadFileHandler csvFileHandler = new UploadFileHandler(
(InputStream content, String fileName, String mimeType) -> {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(content));
String line = br.readLine();
String[] headers = line.split(";");
getUI().get().access(() -> {
grid.removeAllColumns();
// create headers from first row
for (int i = 0; i < headers.length; i++) {
int index = i;
grid.addColumn(lineDataArray -> {
return lineDataArray[index]
;
}).setHeader(headers[index]
);
}
});
// Collect data
List<String[]> records = new ArrayList<>();
while ((line = br.readLine()) != null) {
String[] values = line.split(DELIMITER);
records.add(values);
}
getUI().get().access(() -> {
grid.setItems(records);
});
} catch (IOException ex) {
Logger.getLogger(UploadFileHandlerExample.class.getName()).log(Level.SEVERE, null, ex);
}
});
//Logic to parse CSV columns
private void parseColumnHeadersFromCSV(){
InputStreamReader inputStreamReader = new InputStreamReader(memoryBuffer.getInputStream(), StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
List<String> columnMapping = new ArrayList<>();
try{
String[] strHeaders = bufferedReader.readLine().split(",");
for (String item:strHeaders) {
columnMapping.add(item);
}
}catch (Exception exception){
logger.log(Level.SEVERE, exception.getMessage());
}
csvData.setGridColumns(columnMapping); //Setting value to bean property
}
//Logic to parse CSV row data
private void parseCSVToList(){
try{
InputStreamReader inputStreamReader = new InputStreamReader(memoryBuffer.getInputStream(), StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//Skipping first line of the csv which is grid headers
List<String> list = bufferedReader.lines().skip(1).collect(Collectors.toList());
List<HashMap<String, String>> parsedRows = new ArrayList<>();
for (String item1 : list) {
HashMap<String, String> rowmap = new HashMap<>();
for(int i=0; i<item1.split(",").length; i++){
rowmap.put(csvData.getGridColumns().get(i),item1.split(",")[i]
);
}
parsedRows.add(rowmap);
}
csvData.setGridRows(parsedRows); //Setting value to bean property
}catch (Exception exception){
logger.log(Level.SEVERE,exception.getMessage());
}
}
private void prepareGrid(){
Grid<HashMap<String,String>> grid = new Grid();
grid.addThemeVariants(GridVariant.LUMO_ROW_STRIPES,GridVariant.LUMO_COLUMN_BORDERS,GridVariant.LUMO_COMPACT);
for (String colValues:csvData.getGridColumns()) {
grid.addColumn((ValueProvider<HashMap<String, String>, Object>)
s->{
return s.get(colValues);
}).setHeader(StringUtils.capitalize(colValues)).setFlexGrow(1).setResizable(true);
}
grid.setColumnReorderingAllowed(true);
grid.setDetailsVisibleOnClick(true);
grid.setMultiSort(true);
grid.setSelectionMode(Grid.SelectionMode.SINGLE);
DataProvider<HashMap<String,String>,Void> dataProvider = DataProvider.fromCallbacks(
query -> {
// The index of the first item to load
int offset = query.getOffset();
int limit = query.getLimit();
return csvData.getGridRows().subList(offset,offset+limit).stream();
},
// Second callback fetches the number of items for a query
query -> csvData.getGridRows().size()
);
grid.setDataProvider(dataProvider);
grid.setHeightByRows(false);
this.add(grid);
this.setMargin(true);
}