Import CSV Data into the Grid
Environment
| Product | Progress® KendoReact Grid, Progress® KendoReact Upload |
|---|---|
| Product Version | 16.2.0 |
Description
How can I import data from a CSV file into the KendoReact Grid? Does the Grid provide a built-in CSV import?
This KB also answers the following questions:
- Can I upload a CSV file and show its records in the Grid?
- How do I read the content of a file that is selected in the KendoReact Upload?
- Does the
@progress/kendo-csvpackage parse CSV files?
Solution
The Grid supports exporting data to CSV, but it does not provide a built-in CSV import. The @progress/kendo-csv package that the Grid uses for the export also only generates CSV content.
To import a CSV file, compose the existing components. Use the Upload component to select the file, read the file content with the browser FileReader, parse the text into records, and bind the records to the data property of the Grid.
The following example demonstrates the complete implementation. Download the sample CSV file, and then select it in the Upload to load its records into the Grid.
The solution consists of the following steps:
-
Set the
saveUrlproperty of the Upload to a function. The function receives the selectedUploadFileInfo, and you can read the raw file through itsgetRawFilemethod. Limit the selection to CSV files by using therestrictionsproperty. The following snippet shows the restriction.tsx<Upload restrictions={{ allowedExtensions: ['.csv'] }} saveUrl={onSaveRequest} /> -
In the
saveUrlfunction, read the raw file as text with aFileReader, parse the text, and save the result in the state of the component. The following snippet shows how the demo reads the file.tsxconst reader = new FileReader(); reader.onload = () => { if (typeof reader.result === 'string') { setData(toRecords(reader.result)); resolve({ uid }); } }; reader.readAsText(currentFile.getRawFile!()); -
Bind the records to the Grid, and generate the columns from the keys of the first record.
tsx<Grid data={data}> {Object.keys(data[0]).map((name) => ( <GridColumn key={name} field={name} title={name} /> ))} </Grid>
The
parseCsvfunction in the demo handles quoted fields, escaped quotes, and line breaks inside quoted fields, and it assumes a comma delimiter and a header row. For other CSV dialects or advanced scenarios, use a dedicated CSV parsing library of your choice.