Articles in this section
Category / Section

How to export Flutter DataTable (SfDataGrid) to Excel document and save it as file?

5 mins read

The Syncfusion® Flutter DataTable widget allows you to export the content to Excel with several customizing options.

 

The following steps explains how to export the Syncfusion® Flutter DataTable’s’ content to Excel:

 

STEP 1: Create Employee DataGridSource class by extending the DataGridSource for mapping data to the SfDataGrid.

 

class EmployeeDataGridSource extends DataGridSource {
  EmployeeDataGridSource({required List<Employee> employeeData}) {
    _employeeData = employeeData
        .map<DataGridRow>((Employee dataGridRow) =>
            DataGridRow(cells: <DataGridCell>[
              DataGridCell<int>(columnName: 'ID', value: dataGridRow.id),
              DataGridCell<String>(columnName: 'Name', value: dataGridRow.name),
              DataGridCell<String>(
                  columnName: 'Designation', value: dataGridRow.designation),
              DataGridCell<int>(
                  columnName: 'Salary', value: dataGridRow.salary),
            ]))
        .toList();
  }
 
  List<DataGridRow> _employeeData = <DataGridRow>[];
 
  @override
  List<DataGridRow> get rows => _employeeData;
 
  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((DataGridCell cell) {
      return Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(8.0),
        child: Text(cell.value.toString()),
      );
    }).toList());
  }
}

 

STEP 2: To save the file as an Excel document, it is necessary to include mobile, web, and desktop platform-specific file generating code. So, we have provided the common method as saveAndLaunchFile to save the exported content as a file. We builthave created two dart files (save_file_mobile_desktop and save_file_web) to save and launch the file in on different platforms.

 

To access the path from mobile and desktop platforms, you need to add the path_provider package as a dependency in your application. To download the Excel file in the web platform, you should add AnchorElement from dart:html library in save_file_web file.

 

save_file_web.dart

 

import 'dart:async';
import 'dart:convert';
import 'dart:html';
 
///To save the Excel file in the web platform.
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
  AnchorElement(
      href:
          'data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}')
    ..setAttribute('download', fileName)
    ..click();
}

 

Import io packages in save_file_mobile_desktop file, to save the file. To open the exported file from the given directory, you should import open_file packages.

 

save_file_mobile_desktop.dart

 

import 'dart:io';
 
import 'package:open_file/open_file.dart' as open_file;
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'
    as path_provider_interface;
 
///To save the Excel file in the Mobile and Desktop platforms.
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
  String? path;
  if (Platform.isAndroid ||
      Platform.isIOS ||
      Platform.isLinux ||
      Platform.isWindows) {
    final Directory directory =
        await path_provider.getApplicationSupportDirectory();
    path = directory.path;
  } else {
    path = await path_provider_interface.PathProviderPlatform.instance
        .getApplicationSupportPath();
  }
 
  final String fileLocation =
      Platform.isWindows ? '$path\\$fileName' : '$path/$fileName';
  final File file = File(fileLocation);
  await file.writeAsBytes(bytes, flush: true);
 
  if (Platform.isAndroid || Platform.isIOS) {
    await open_file.OpenFile.open(fileLocation);
  } else if (Platform.isWindows) {
    await Process.run('start', <String>[fileLocation], runInShell: true);
  } else if (Platform.isMacOS) {
    await Process.run('open', <String>[fileLocation], runInShell: true);
  } else if (Platform.isLinux) {
    await Process.run('xdg-open', <String>[fileLocation], runInShell: true);
  }
}

 

STEP 3: Initialize the SfDataGrid widget with all the required properties. Create the GlobalKey using the SfDataGridState and set the key to the DataGrid.

 

Import the save_file_mobile_desktop and save_file_web.dart files.

 

Call the exportToExcelWorkbook method from MaterialButton’s’ onPressed callback and pass the exported workbook’s’ bytes to saveAndLaunchFile method.

 

  import 'helper/save_file_mobile_desktop.dart'
    if (dart.library.html) 'helper/save_file_web.dart' as helper;
 
  List<Employee> employees = <Employee>[];
  late EmployeeDataGridSource employeeDataGridSource;
  final GlobalKey<SfDataGridState> _key = GlobalKey<SfDataGridState>();
 
  @override
  void initState() {
    super.initState();
    employees = getEmployeeData();
    employeeDataGridSource = EmployeeDataGridSource(employeeData: employees);
  }
 
  Future<void> exportDataGridToExcel() async {
    final Workbook workbook = _key.currentState!.exportToExcelWorkbook();
    final List<int> bytes = workbook.saveAsStream();
    workbook.dispose();
    await helper.saveAndLaunchFile(bytes, 'DataGrid.xlsx');
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Syncfusion Flutter DataGrid Export')),
        body: Column(children: <Widget>[
          Container(
              margin: const EdgeInsets.all(12.0),
              child: Row(children: <Widget>[
                SizedBox(
                    height: 40.0,
                    width: 150.0,
                    child: MaterialButton(
                        color: Colors.blue,
                        child: const Center(
                            child: Text('Export to Excel',
                                style: TextStyle(color: Colors.white))),
                        onPressed: exportDataGridToExcel))
              ])),
          Expanded(
              child: SfDataGrid(
                  key: _key,
                  source: employeeDataGridSource,
                  columns: <GridColumn>[
                GridColumn(
                    columnName: 'ID',
                    label: Container(
                        padding: const EdgeInsets.all(16.0),
                        alignment: Alignment.center,
                        child: const Text('ID'))),
                GridColumn(
                    columnName: 'Name',
                    label: Container(
                        padding: const EdgeInsets.all(8.0),
                        alignment: Alignment.center,
                        child: const Text('Name'))),
                GridColumn(
                    columnName: 'Designation',
                    label: Container(
                        padding: const EdgeInsets.all(8.0),
                        alignment: Alignment.center,
                        child: const Text('Designation',
                            overflow: TextOverflow.ellipsis))),
                GridColumn(
                    columnName: 'Salary',
                    label: Container(
                        padding: const EdgeInsets.all(8.0),
                        alignment: Alignment.center,
                        child: const Text('Salary')))
              ]))
        ]));
  }

 

You can go through this UG link to know more about the Excel exporting.

 

View the GitHub sample here.


Conclusion

I hope you enjoyed learning about how to export Flutter DataTable (SfDataGrid) to Excel document and save it as file.

You can refer to our Flutter DataGrid featuretour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Flutter widgets example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied