|
1 | | -# How-to-import-an-excel-file-into-Flutter-DataTable- |
2 | | -This demo shows how to import an excel file into Flutter DataTable. |
| 1 | +# How to import an excel file into Flutter DataTable (SfDataGrid)? |
| 2 | + |
| 3 | +In this article, we will show you how to import an excel file into [Flutter DataTable](https://www.syncfusion.com/flutter-widgets/flutter-datagrid). |
| 4 | + |
| 5 | +## Steps to Import an Excel File into Flutter DataTable |
| 6 | + |
| 7 | +### Step 1: Extracting Data from Excel |
| 8 | + |
| 9 | +The file picker should allow the selection of .xlsx files. Once an Excel file is selected, decode it using the `Excel.decodeBytes` method from the excel package. Extract the headers from the first row and the data starting from the second row. Dynamically generate columns by iterating over the headers and creating a [GridColumn](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/GridColumn-class.html) for each one. |
| 10 | + |
| 11 | +```dart |
| 12 | + // Handle Excel file import and load data into the DataGrid. |
| 13 | + Future<void> importDataGridFromExcel() async { |
| 14 | + clearData(); |
| 15 | +
|
| 16 | + // Picking an Excel file using FilePicker. |
| 17 | + FilePickerResult? result = await FilePicker.platform.pickFiles( |
| 18 | + type: FileType.custom, |
| 19 | + allowedExtensions: ['xlsx'], |
| 20 | + ); |
| 21 | +
|
| 22 | + if (result != null) { |
| 23 | + Uint8List? fileBytes = result.files.first.bytes; |
| 24 | + if (fileBytes == null) { |
| 25 | + String? filePath = result.files.first.path; |
| 26 | + if (filePath != null) { |
| 27 | + fileBytes = await File(filePath).readAsBytes(); |
| 28 | + } |
| 29 | + } |
| 30 | +
|
| 31 | + if (fileBytes != null) { |
| 32 | + var excel = Excel.decodeBytes(fileBytes); |
| 33 | +
|
| 34 | + for (var table in excel.tables.keys) { |
| 35 | + var sheet = excel.tables[table]; |
| 36 | + // Extract headers from the first row of the sheet. |
| 37 | + List<String> headers = |
| 38 | + sheet!.row(0).map((cell) => cell!.value.toString()).toList(); |
| 39 | + // Loop through the rows starting from the second row (skipping the header). |
| 40 | + for (int row = 1; row < sheet.maxRows; row++) { |
| 41 | + Map<String, dynamic> rowData = {}; |
| 42 | + for (int col = 0; col < headers.length; col++) { |
| 43 | + rowData[headers[col]] = sheet.row(row)[col]!.value; |
| 44 | + } |
| 45 | + importedData.add(rowData); |
| 46 | + } |
| 47 | + } |
| 48 | +
|
| 49 | + if (importedData.isNotEmpty) { |
| 50 | + // Generate the columns. |
| 51 | + columns = generateColumns(importedData[0]); |
| 52 | + if (mounted) { |
| 53 | + Navigator.push( |
| 54 | + context, |
| 55 | + MaterialPageRoute( |
| 56 | + builder: (context) => DataGridPage( |
| 57 | + importedData: importedData, |
| 58 | + columns: columns, |
| 59 | + ), |
| 60 | + ), |
| 61 | + ); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +
|
| 68 | + // Clear previous data. |
| 69 | + void clearData() { |
| 70 | + importedData.clear(); |
| 71 | + columns.clear(); |
| 72 | + } |
| 73 | +
|
| 74 | + // Dynamically generate columns based on the imported data. |
| 75 | + List<GridColumn> generateColumns(Map<String, dynamic> data) { |
| 76 | + List<GridColumn> columns = []; |
| 77 | +
|
| 78 | + for (var entry in data.entries) { |
| 79 | + GridColumn gridColumn = GridColumn( |
| 80 | + columnName: entry.key, |
| 81 | + label: Container( |
| 82 | + padding: const EdgeInsets.all(8), |
| 83 | + alignment: Alignment.center, |
| 84 | + child: Text(entry.key), |
| 85 | + ), |
| 86 | + ); |
| 87 | +
|
| 88 | + columns.add(gridColumn); |
| 89 | + } |
| 90 | +
|
| 91 | + return columns; |
| 92 | + } |
| 93 | +``` |
| 94 | + |
| 95 | +### Step 2: Displaying Data in SfDataGrid |
| 96 | + |
| 97 | +Display a CircularProgressIndicator while the data is loading. Once the data is loaded, pass the prepared DataGridSource to the [SfDataGrid]() widget to render the grid. |
| 98 | + |
| 99 | +```dart |
| 100 | + late ExcelDataGridSource excelDataGridSource; |
| 101 | + bool isLoading = true; |
| 102 | +
|
| 103 | + @override |
| 104 | + void initState() { |
| 105 | + super.initState(); |
| 106 | + loadData(); |
| 107 | + } |
| 108 | +
|
| 109 | + // Simulate loading data and prepare the DataGrid source. |
| 110 | + Future<void> loadData() async { |
| 111 | + await Future.delayed(const Duration(seconds: 2)); |
| 112 | + if (mounted) { |
| 113 | + setState(() { |
| 114 | + excelDataGridSource = |
| 115 | + ExcelDataGridSource(widget.importedData, widget.columns); |
| 116 | + isLoading = false; |
| 117 | + }); |
| 118 | + } |
| 119 | + } |
| 120 | +
|
| 121 | + @override |
| 122 | + Widget build(BuildContext context) { |
| 123 | + return Scaffold( |
| 124 | + appBar: AppBar( |
| 125 | + title: const Text('DataGrid'), |
| 126 | + ), |
| 127 | + body: isLoading |
| 128 | + ? const Center(child: CircularProgressIndicator()) |
| 129 | + : SfDataGrid( |
| 130 | + source: excelDataGridSource, |
| 131 | + columns: widget.columns, |
| 132 | + columnWidthMode: ColumnWidthMode.fill, |
| 133 | + ), |
| 134 | + ); |
| 135 | + } |
| 136 | +``` |
| 137 | + |
| 138 | +You can download this example on [GitHub](https://github.com/SyncfusionExamples/How-to-import-an-excel-file-into-Flutter-DataTable). |
0 commit comments