Easily Export DataGrid to Excel and PDF in Flutter | Syncfusion Blogs
Detailed Blog page Skeleton loader
Easily Export DataGrid to Excel and PDF in Flutter

We at Syncfusion have added an essential feature in our Flutter DataGrid in the 2021 Volume 3 release. You can now export the Flutter DataGrid content such as column headers, rows, stacked header rows, and table summary rows to Excel and PDF documents, and customize the content that you export.

In this blog, we’ll learn how to easily export the Flutter DataGrid to Excel and PDF documents.

How to export DataGrid to Excel and PDF

You can get both the Excel and PDF exporting functionalities in the syncfusion_flutter_datagrid_export package. We are using our xlsio and pdf packages to export the DataGrid content to Excel and PDF, respectively.

Let’s see how it’s done!

Step 1: First, add the syncfusion_flutter_datagrid_export package as a dependency in your pubspec.yaml file.

dependencies:
syncfusion_flutter_datagrid_export: ^xx.x.xx

Step 2: Then, import the following files into your application:

import 'package:syncfusion_flutter_datagrid_export/export.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'package:syncfusion_flutter_xlsio/xlsio.dart'

Step 3: Now, add the Flutter DataGrid with two buttons: one for exporting to Excel, and another for exporting to PDF format.

Refer to the following code.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Syncfusion Flutter DataGrid Export',
          overflow: TextOverflow.ellipsis,
        ),
      ),
      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),
                ),
                const Padding(padding: EdgeInsets.all(20)),
                SizedBox(
                  height: 40.0,
                  width: 150.0,
                  child: MaterialButton(
                      color: Colors.blue,
                      child: const Center(
                          child: Text(
                        'Export to PDF',
                        style: TextStyle(color: Colors.white),
                      )),
                      onPressed: exportDataGridToPdf),
                ),
              ],
            ),
          ),
          Expanded(
            child: SfDataGrid(
              source: employeeDataSource,
              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'))),
              ],
            ),
          ),
        ],
      ),
    );
  }

Step 4: All the exporting-related methods are provided as extension methods in the SfDataGridState class. So, we have to create the GlobalKey with the SfDataGridState and assign the created key to the SfDataGrid.

Refer to the following code.

final GlobalKey<SfDataGridState> _key = GlobalKey<SfDataGridState>();

…..
          child: SfDataGrid(
            key: _key,
…..

Step 5: To export to Excel, you can access the exporting-related methods in the Flutter DataGrid through the _key.currentState! property. The following methods are available for Excel exporting:

  • exportToWorkbook
  • exportToWorksheet

When you call these methods, you don’t need to pass the rows or columns. They will be automatically taken from the corresponding DataGrid.

In the following code snippet, we perform the Excel exporting inside the Export To Excel button’s onPressed callback.

  void exportDataGridToExcel(){
    final Workbook workbook = _key.currentState!.exportToExcelWorkbook();
    final List<int> bytes = workbook.saveAsStream();
    File('DataGrid.xlsx').writeAsBytes(bytes);
    workbook.dispose();
  }

Note: For more details, refer to the Create an Excel document in mobile, web, and desktop documentations.

Step 6: To export to PDF, you can access the exporting-related methods in the Flutter DataGrid through the _key.currentState! property. The following methods are available for PDF exporting:

  • exportToPdfDocument
  • exportToPdfGrid

In the following code snippet, we perform the PDF exporting inside the Export To PDF button’s onPressed callback.

  Void exportDataGridToPdf() {
    final PdfDocument document =
        _key.currentState!.exportToPdfDocument();

    final List<int> bytes = document.save();
    File('DataGrid.pdf').writeAsBytes(bytes);
    document.dispose();
  }

Note: For more details, refer to the save and download a PDF document on the web and mobile documentations.

That’s all there is to it. If you press these Export to Excel and Export to PDF buttons, then the DataGrid content will be exported to Excel and PDF formats, respectively.

Export customization

As I mentioned at the beginning, you can also perform several customizations while exporting the Flutter DataGrid. Excel and PDF exporting have different kinds of customizations based on their document behavior. They are:

  • Excel
    • Export columns with the same width as in the DataGrid.
    • Exclude some columns from being exported.
    • Set the starting row and column indexes in an Excel sheet from where the DataGrid content should be started.
  • PDF
    • Fit all the columns in a page instead of overflowing to another page.
    • Repeat the column headers on each page.
    • Exclude some columns from being exported.

Note: Refer to the export To Excel and export To PDF documentations for more details.

Conclusion

Thanks for reading! I hope you now have enough information about the new exporting feature in the Flutter DataGrid that rolled out in the 2021 Volume 3 release. This feature is also listed in our Release Notes and What’s New pages. Try out this incredible feature and enjoy hassle-free exporting!

Browse our Flutter documentation for complete details about our Flutter widgets. You can also see Syncfusion’s Flutter app with many examples in this GitHub repository. Don’t miss our demo app in Google Play and the App Store.

If you are not a customer yet, you can try our 30-day free trial to check out these features.

Also, you can contact us through our support forumfeedback portal, or Direct-Trac support system. We are always happy to assist you!

Related blogs

Be the first to get updates

Neelakandan Kannan

Meet the Author

Neelakandan Kannan

Neelakandan Kannan is a product manager at Syncfusion. He has been a .NET developer since 2014 with expertise in Flutter, WinForms and WPF.

Comments (2)

Have can we export 2 Datagrid into 1 PDF file?

@ Ayberk  

To fulfill your requirement, you can make use of the `exportToPdfGrid` method provided by the Syncfusion DataGrid. This method enables you to export the DataGrid’s content to a PDF grid. To implement this functionality, follow these steps:

1. Create a PDF document at the sample level.
2. Utilize the `exportToPdfGrid` method to export the relevant DataGrid contents into the document’s pages.

To assist you further, we have prepared a simple sample application along with a code snippet that illustrates the process of exporting multiple DataGrid contents to a PDF document. Please refer to them for a comprehensive understanding of how to accomplish this task.

final GlobalKey _firstDatagridKey =
GlobalKey();
final GlobalKey _secondDatagridKey =
GlobalKey();

@override
void initState() {
super.initState();
employees = getEmployeeData();
employees2 = getEmployeeData2();
_employeeDataSource = EmployeeDataSource(employees);
_employeeDataSource2 = EmployeeDataSource(employees2);
}

Future exportDataGridToPdf() async {

final PdfDocument document = PdfDocument();

final PdfGrid firstPDFGrid = _firstDatagridKey.currentState!
.exportToPdfGrid(fitAllColumnsInOnePage: true);

final PdfGrid secondPDFGrid = _secondDatagridKey.currentState!
.exportToPdfGrid(fitAllColumnsInOnePage: true);

firstPDFGrid.draw(
page: document.pages.add(), bounds: const Rect.fromLTWH(0, 0, 0, 0));

secondPDFGrid.draw(
page: document.pages.add(), bounds: const Rect.fromLTWH(0, 0, 0, 0));

final List bytes = document.saveSync();
await helper.saveAndLaunchFile(bytes, ‘DataGrid.pdf’);
document.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(‘Syncfusion Flutter DataGrid Demo’),
),
body: Column(children: [
Container(
margin: const EdgeInsets.symmetric(vertical: 15),
child: SizedBox(
child: ElevatedButton(
onPressed: exportDataGridToPdf,
child: const Text(‘Export DataGrid to PDF’))),
),
Container(
height: 30,
width: MediaQuery.of(context).size.width,
color: Colors.teal,
child: const Center(child: Text(‘Employee DataGrid 1’)),
),
SizedBox(
height: 200,
child: SfDataGrid(
source: _employeeDataSource,
key: _firstDatagridKey,
columns: getColumns,
columnWidthMode: ColumnWidthMode.fill),
),
Container(
height: 30,
width: MediaQuery.of(context).size.width,
color: Colors.teal,
child: const Center(child: Text(‘Employee DataGrid 2’)),
),
Expanded(
child: SfDataGrid(
source: _employeeDataSource2,
key: _secondDatagridKey,
columns: getColumns,
columnWidthMode: ColumnWidthMode.fill),
),
]),
);
}
}

Comments are closed.