Easily Export DataGrid to Excel and PDF in Flutter | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (180).NET Core  (28).NET MAUI  (224)Angular  (113)ASP.NET  (49)ASP.NET Core  (81)ASP.NET MVC  (87)Azure  (41)Black Friday Deal  (1)Blazor  (234)BoldSign  (14)DocIO  (24)Essential JS 2  (110)Essential Studio  (199)File Formats  (72)Flutter  (135)JavaScript  (226)Microsoft  (121)PDF  (83)Python  (1)React  (105)Streamlit  (1)Succinctly series  (131)Syncfusion  (960)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (46)Webinar  (53)Windows Forms  (59)WinUI  (72)WPF  (162)Xamarin  (159)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (10)Business intelligence  (55)Button  (4)C#  (163)Chart  (145)Chart of the week  (57)Cloud  (15)Company  (440)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (73)Development  (676)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (13)Excel  (43)Extensions  (23)File Manager  (7)Gantt  (20)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (519)Mobile MVC  (9)OLAP server  (2)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (45)Performance  (13)PHP  (2)PivotGrid  (5)Predictive Analytics  (6)Report Server  (3)Reporting  (8)Reporting / Back Office  (9)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (5)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (32)Solution Services  (4)Spreadsheet  (11)SQL  (15)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (113)UI  (400)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (624)What's new  (337)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Easily Export DataGrid to Excel and PDF in Flutter

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

Tags:

Share this post:

Comments (2)

Have can we export 2 Datagrid into 1 PDF file?

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.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed