Easily Export WinUI DataGrid to Excel | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (181).NET Core  (28).NET MAUI  (227)Angular  (113)ASP.NET  (49)ASP.NET Core  (81)ASP.NET MVC  (87)Azure  (42)Black Friday Deal  (1)Blazor  (236)BoldSign  (14)DocIO  (24)Essential JS 2  (110)Essential Studio  (200)File Formats  (73)Flutter  (136)JavaScript  (226)Microsoft  (122)PDF  (83)Python  (1)React  (105)Streamlit  (1)Succinctly series  (131)Syncfusion  (964)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (46)Webinar  (53)Windows Forms  (59)WinUI  (72)WPF  (163)Xamarin  (159)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (11)Business intelligence  (55)Button  (4)C#  (164)Chart  (147)Chart of the week  (58)Cloud  (15)Company  (440)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (73)Development  (681)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (13)Excel  (43)Extensions  (23)File Manager  (7)Gantt  (21)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  (522)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  (112)UI  (406)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (628)What's new  (341)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Easily Export WinUI DataGrid to Excel

Easily Export WinUI DataGrid to Excel

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 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.

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: To add the WinUI DataGrid control.
  2. Syncfusion.GridExport.WinUI: To export the DataGrid to Excel files.

Add the necessary NuGet packages

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

<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 class. By using the ExportToExcel method, you can export the DataGrid content to an Excel workbook and save it as an Excel file. The DataGridExcelExportExtensions class provides the extension methods for exporting the data from the DataGrid.

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

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.

Exporting WinUI DataGrid's data to Excel
Exporting WinUI DataGrid’s data to Excel

Customizing the Excel exporting

We can also customize the export operation using the DataGridExcelExportOptions. 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 property while exporting.

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.

Exporting stacked headers in WinUI DataGrid to Excel
Exporting stacked headers in WinUI DataGrid to Excel

Excluding specific DataGrid columns during export

By default, all columns are exported, including those that are hidden. You can exclude specific data columns 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.

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.

Excluding specific columns in WinUI DataGrid while exporting to an Excel file
Excluding specific columns in WinUI DataGrid while exporting to an Excel file

Exporting the selected rows

Let’s see how to export only the selected rows in a DataGrid using the ExportToExcel method and passing instances of the SelectedItems collection.

Refer to the following code example.

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.

Exporting only selected rows in WinUI DataGrid to Excel
Exporting only selected rows in WinUI DataGrid to Excel

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 and StartColumnIndex properties, respectively.

Refer to the code example.

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.

Customizing the starting row and column position in the exported Excel file
Customizing the starting row and column position in the exported Excel file

Applying row style while exporting

Let’s apply styles for cells or rows in the WinUI DataGrid while exporting using the CellsExportHandler. Here, the exported rows can be styled based on the Grid data.

Refer to the following code example.

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.

Applying row style while exporting to Excel
Applying row style while exporting to Excel

References

For more details, refer to Export WinUI DataGrid to Excel documentation and GitHub demo.

Conclusion

Thanks for reading! In this blog, we’ve explored how to export the Syncfusion 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. 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 page. If you are not a Syncfusion customer, feel free to download our free evaluation to discover all our controls.

You can also contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed