Easily Export WinUI DataGrid to Excel
Tags: winui, datagrid, excel, export
Published: 2024-04-30 09:53:39

---
title: Easily Export WinUI DataGrid to Excel
published: true
date: 2024-04-29 15:38:14 UTC
tags: winui, datagrid, excel, export
canonical_url: https://www.syncfusion.com/blogs/post/export-winui-datagrid-to-excel
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tq1h49hq5r23tdgw8aq0.png
---
**TL;DR:** Explore how to export data from the Syncfusion WinUI DataGrid to an Excel document. We covered topics, such as custom export options, styling exported rows, and exporting only selected rows.

The Syncfusion [WinUI DataGrid](https://www.syncfusion.com/winui-controls/datagrid "WinUI DataGrid") is designed to display and manipulate tabular data efficiently. Its comprehensive feature set includes data binding, editing, sorting, filtering, and grouping. It is also optimized for handling millions of records and can easily manage high-frequency, real-time updates.

In this blog, we’ll explore how to export WinUI DataGrid data to an Excel file with code examples.

**Note:** Before proceeding, refer to the getting started with [WinUI DataGrid documentation](https://help.syncfusion.com/winui/datagrid/getting-started "Getting started with WinUI DataGrid").

## Exporting WinUI DataGrid to Excel

To export the WinUI DataGrid’s data to an Excel document, we should add the following NuGet packages in our app:

1.[Syncfusion.Grid.WinUI](https://www.nuget.org/packages/Syncfusion.Grid.WinUI "Syncfusion.Grid.WinUI NuGet package"): To add the WinUI DataGrid control.
2.[Syncfusion.GridExport.WinUI](https://www.nuget.org/packages/Syncfusion.GridExport.WinUI "Syncfusion.GridExport.WinUI NuGet package"): To export the DataGrid to Excel files.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/04/Syncfusion-Grid-WinUI-packages.png" alt="Add the necessary NuGet packages" style="width:100%">

  <figcaption></figcaption>

</figure>

Now, initialize the WinUI DataGrid control on your XAML page.

```xml
<dataGrid:SfDataGrid x:Name="SfDataGrid" 
                     DataContext="{StaticResource orderInfoViewModel}"
                     ItemsSource="{Binding OrdersDetails}"
                     GridLinesVisibility="Both"
                     AutoGenerateColumns="False"
                     ColumnWidthMode="Auto">
    <dataGrid:SfDataGrid.Columns>
        <dataGrid:GridNumericColumn HeaderText="Order ID" MappingName="OrderID" TextAlignment="Right"/>
        <dataGrid:GridDateColumn MappingName="OrderDate" HeaderText="Order Date" TextAlignment="Right" />
        <dataGrid:GridTextColumn HeaderText="Shipping City" MappingName="ShipCity" />
        <dataGrid:GridTextColumn HeaderText="Shipping Country" MappingName="ShipAddress" />
        <dataGrid:GridTextColumn HeaderText="Quantity" MappingName="Quantity" TextAlignment="Right"/>
        <dataGrid:GridNumericColumn HeaderText="Unit Price" MappingName="UnitPrice" DisplayNumberFormat="C2" Width="165" />
    </dataGrid:SfDataGrid.Columns>
</dataGrid:SfDataGrid>

```

All the methods for Excel exporting are available in the [DataGridToExcelConverter](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridToExcelConverter.html "DataGridToExcelConverter class of WinUI DataGrid") class. By using the [ExportToExcel](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridToExcelConverter.html#Syncfusion_UI_Xaml_DataGrid_Export_DataGridToExcelConverter_ExportToExcel_Syncfusion_UI_Xaml_DataGrid_SfDataGrid_Syncfusion_UI_Xaml_Data_ICollectionViewAdv_Syncfusion_UI_Xaml_DataGrid_Export_DataGridExcelExportOptions_ "ExportToExcel method of WinUI DataGrid") method, you can export the DataGrid content to an Excel workbook and save it as an Excel file. The [DataGridExcelExportExtensions](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportExtensions.html "DataGridExcelExportExtensions class of WinUI DataGrid") class provides the [extension methods](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportExtensions.html#methods "ExporttoExcel method of WinUI DataGrid") for exporting the data from the DataGrid.

Refer to the following code example to export the data to an Excel file.

```csharp
private void OnExportToExcelClick(object sender, RoutedEventArgs e)
{
    var options = new DataGridExcelExportOptions();
    options.ExcelVersion = ExcelVersion.Excel2013;
    var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.View, options);
    
    var workBook = excelEngine.Excel.Workbooks[0];
    MemoryStream outputStream = new MemoryStream();
    workBook.SaveAs(outputStream);
    SaveExcelWorkbook(outputStream, "OrderDetails");
}
async void SaveExcelWorkbook(MemoryStream stream, string filename)
{
    StorageFile stFile;
    if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
    {
        FileSavePicker savePicker = new FileSavePicker();
        savePicker.DefaultFileExtension = ".xlsx";
        savePicker.SuggestedFileName = filename;
        savePicker.FileTypeChoices.Add("Excel Documents", new List<string>() { ".xlsx" });
        var hwnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
        WinRT.Interop.InitializeWithWindow.Initialize(savePicker, hwnd);
        stFile = await savePicker.PickSaveFileAsync();
    }
    else
    {
        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
        stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    }
    if (stFile != null)
    {
        using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            //Write compressed data from memory to file.
            using (Stream outstream = zipStream.AsStreamForWrite())
            {
                byte[] buffer = stream.ToArray();
                outstream.Write(buffer, 0, buffer.Length);
                outstream.Flush();
            }
        }
        //Launch the saved Excel file.
        await Windows.System.Launcher.LaunchFileAsync(stFile);
    }
}

```

Refer to the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/04/Exporting-WinUI-DataGrids-data-to-Excel.png" alt="Exporting WinUI DataGrid's data to Excel" style="width:100%">

  <figcaption>Exporting WinUI DataGrid's data to Excel</figcaption>

</figure>

## Customizing the Excel exporting

We can also customize the export operation using the [DataGridExcelExportOptions](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportOptions.html "DataGridExcelExportOptions class of WinUI DataGrid"). Let’s see how to do so!

### Export the DataGrid’s stacked headers to Excel

By default, only the column headers of the WinUI DataGrid will be exported. However, if you want to include the stacked headers in the exported Excel file, you can enable the [CanExportStackedHeaders](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportOptions.html#Syncfusion_UI_Xaml_DataGrid_Export_DataGridExcelExportOptions_CanExportStackedHeaders "CanExportStackedHeaders property of WinUI DataGrid") property while exporting.

```csharp
private void OnExportDataGridClick(object sender, RoutedEventArgs e)
{
    var options = new DataGridExcelExportOptions();
    options.ExcelVersion = ExcelVersion.Excel2013;
    
    options.CanExportStackedHeaders = true;
    
    var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.View, options);
    var workBook = excelEngine.Excel.Workbooks[0];
    MemoryStream outputStream = new MemoryStream();
    workBook.SaveAs(outputStream);
    SaveExcelWorkbook(outputStream, "OrderDetails");
}

```

Refer to the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/04/Exporting-stacked-headers-in-WinUI-DataGrid-to-Excel.png" alt="Exporting stacked headers in WinUI DataGrid to Excel" style="width:100%">

  <figcaption>Exporting stacked headers in WinUI DataGrid to Excel</figcaption>

</figure>

### Excluding specific DataGrid columns during export

By default, all columns are exported, including those that are hidden. You can [exclude specific data columns](https://help.syncfusion.com/winui/datagrid/export-to-excel#exclude-columns-while-exporting "Exclude specific columns in WinUI DataGrid while exporting to Excel") in a grid from being exported to an Excel sheet.

Refer to the following code example. Here, the **OrderDate** and **ShipAddress** columns are excluded while exporting to Excel.

```csharp
private void OnExportToExcelClick(object sender, RoutedEventArgs e)
{
    var options = new DataGridExcelExportOptions();
    options.ExcelVersion = ExcelVersion.Excel2013;
  
    options.ExcludedColumns.Add("OrderDate");
    options.ExcludedColumns.Add("ShipAddress");
    
    var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.View, options);
    
    var workBook = excelEngine.Excel.Workbooks[0];
    MemoryStream outputStream = new MemoryStream();
    workBook.SaveAs(outputStream);
    SaveExcelWorkbook(outputStream, "OrderDetails");
}

```

Refer to the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/04/Excluding-specific-columns-in-WinUI-DataGrid-while-exporting-to-an-Excel-file-1024x428.png" alt="Excluding specific columns in WinUI DataGrid while exporting to an Excel file" style="width:100%">

  <figcaption>Excluding specific columns in WinUI DataGrid while exporting to an Excel file</figcaption>

</figure>

### Exporting the selected rows

Let’s see how to export only the selected rows in a DataGrid using the [ExportToExcel](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportExtensions.html#Syncfusion_UI_Xaml_DataGrid_Export_DataGridExcelExportExtensions_ExportToExcel_Syncfusion_UI_Xaml_DataGrid_SfDataGrid_System_Collections_ObjectModel_ObservableCollection_System_Object__Syncfusion_UI_Xaml_DataGrid_Export_DataGridExcelExportOptions_ "ExportToExcel method of WinUI DataGrid") method and passing instances of the [SelectedItems](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.Grids.SfGridBase.html#Syncfusion_UI_Xaml_Grids_SfGridBase_SelectedItems "SelectedItems property of WinUI DataGrid") collection.

Refer to the following code example.

```csharp
private void OnExportSelectedRowsClick(object sender, RoutedEventArgs e)
{
    var options = new DataGridExcelExportOptions();
    options.ExcelVersion = ExcelVersion.Excel2013;
    var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.SelectedItems, options);
    
    var workBook = excelEngine.Excel.Workbooks[0];
    MemoryStream outputStream = new MemoryStream();
    workBook.SaveAs(outputStream);
    SaveExcelWorkbook(outputStream, "SelectedOrders");
}

```

Refer to the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/04/Exporting-only-selected-rows-in-WinUI-DataGrid-to-Excel-1024x372.png" alt="Exporting only selected rows in WinUI DataGrid to Excel" style="width:100%">

  <figcaption>Exporting only selected rows in WinUI DataGrid to Excel</figcaption>

</figure>

### Customizing the starting row and column position in Excel

You can also customize the starting position of the row and column in the exported Excel sheet using the [StartRowIndex](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportOptions.html#Syncfusion_UI_Xaml_DataGrid_Export_DataGridExcelExportOptions_StartRowIndex "StartRowIndex property of WinUI DataGrid") and [StartColumnIndex](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportOptions.html#Syncfusion_UI_Xaml_DataGrid_Export_DataGridExcelExportOptions_StartColumnIndex "StartColumnIndex property of WinUI DataGrid") properties, respectively.

Refer to the code example.

```csharp
private void OnExportToExcelClick(object sender, RoutedEventArgs e)
{
    var options = new DataGridExcelExportOptions();
    options.ExcelVersion = ExcelVersion.Excel2013;
    
    options.StartRowIndex = 4;
    options.StartColumnIndex = 2;
    
    var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.View, options);
    var workBook = excelEngine.Excel.Workbooks[0];
    MemoryStream outputStream = new MemoryStream();
    workBook.SaveAs(outputStream);
    SaveExcelWorkbook(outputStream, "OrderDetails");
}

```

Refer to the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/04/Customizing-the-starting-row-and-column-position-in-the-exported-Excel-file-1024x421.png" alt="Customizing the starting row and column position in the exported Excel file" style="width:100%">

  <figcaption>Customizing the starting row and column position in the exported Excel file</figcaption>

</figure>

### Applying row style while exporting

Let’s apply styles for cells or rows in the WinUI DataGrid while exporting using the [CellsExportHandler](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.DataGrid.Export.DataGridExcelExportOptions.html#Syncfusion_UI_Xaml_DataGrid_Export_DataGridExcelExportOptions_CellsExportHandler "CellsExportHandler property of WinUI DataGrid"). Here, the exported rows can be styled based on the Grid data.

Refer to the following code example.

```csharp
private void OnExportToExcelClick(object sender, RoutedEventArgs e)
{
    var options = new DataGridExcelExportOptions();
    options.ExcelVersion = ExcelVersion.Excel2013;
    
    options.CellsExportHandler = CellsExportHandler;	
    
    var excelEngine = sfDataGrid.ExportToExcel(sfDataGrid.View, options);
    var workBook = excelEngine.Excel.Workbooks[0];
    MemoryStream outputStream = new MemoryStream();
    workBook.SaveAs(outputStream);
    SaveExcelWorkbook(outputStream, "OrderDetails");
}
private void CellsExportHandler(object sender, DataGridCellExcelExportOptions e)
{
    var record = e.NodeEntry;
    if (record != null && (record as OrderInfo).ShipAddress == "Brazil")
    {
        e.Range.CellStyle.ColorIndex = ExcelKnownColors.Blue_grey;
        e.Range.CellStyle.Font.Color = ExcelKnownColors.Light_yellow;
    }
}

```

Refer to the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/04/Applying-row-style-while-exporting-to-Excel-1024x415.png" alt="Applying row style while exporting to Excel" style="width:100%">

  <figcaption>Applying row style while exporting to Excel</figcaption>

</figure>

## References

For more details, refer to [Export WinUI DataGrid to Excel documentation](https://help.syncfusion.com/winui/datagrid/export-to-excel "Export WinUI DataGrid To Excel documentation") and [GitHub demo](https://github.com/SyncfusionExamples/export-winui-datagrid-to-excel "Export WinUI DataGrid To Excel GitHub demo").

## Conclusion

Thanks for reading! In this blog, we’ve explored how to export the Syncfusion [WinUI DataGrid](https://www.syncfusion.com/winui-controls/datagrid "WinUI DataGrid") data to an Excel document. We encourage you to try these steps and share your feedback in the comments below.

Our WinUI demo app is available for download on the [Microsoft Store](https://apps.microsoft.com/detail/9n0fp16ddc06?ocid=pdpshare&hl=en-us&gl=us "Syncfusion WinUI demos on the Microsoft Store"). We would love to hear your feedback after you’ve tried it, so please leave your thoughts in the comment section below.

For our existing customers, the latest version of Essential Studio for WinUI is accessible from the [License and Downloads](https://www.syncfusion.com/account/downloads "Essential Studio License and Downloads page") page. If you are not a Syncfusion customer, feel free to download our [free evaluation](https://www.syncfusion.com/downloads "Free evaluation of the Essential Studio products") to discover all our controls.

You can also contact us through our [support forum](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Easily Load Appointments in WinUI Scheduler with SQLite and Perform CRUD Actions](https://www.syncfusion.com/blogs/post/winui-scheduler-sqlite-crud "Blog: Easily Load Appointments in WinUI Scheduler with SQLite and Perform CRUD Actions")
- [From Stars to Hearts: Explore Creative Rating Designs in WinUI](https://www.syncfusion.com/blogs/post/creative-rating-designs-winui "Blog: From Stars to Hearts: Explore Creative Rating Designs in WinUI")
- [Chart of the Week: Creating a WinUI Stacked Area Chart to Visualize US Primary Energy Consumption](https://www.syncfusion.com/blogs/post/winui-stacked-area-chart-energy-consumption "Blog: Chart of the Week: Creating a WinUI Stacked Area Chart to Visualize US Primary Energy Consumption")
- [Introducing the New WinUI Shimmer Control](https://www.syncfusion.com/blogs/post/new-winui-shimmer-control "Blog: Introducing the New WinUI Shimmer Control")