﻿# DataGrid: Export to Excel and CSV

Export a Radzen Blazor DataGrid to Excel and CSV directly in the browser, including chunked LoadData exports.

Keywords: export, excel, csv, datagrid

> API reference: [RadzenDataGrid API](https://blazor.radzen.com/docs/api/Radzen.Blazor.RadzenDataGrid-1.md)

## Examples

## Blazor DataGrid Export to Excel and CSV

Export a Blazor DataGrid to Excel and CSV directly in the browser - no server required. Choose between the current page and all rows; exports respect the current sort, filter, column order, format strings, and theme - colors, gridlines and font size, including compact density.

### Export

Call `ExportToExcelAsync` or `ExportToCsvAsync` and pick a scope - the current page or all filtered and sorted rows.

```razor
@inherits DbContextPage

<RadzenCard Variant="Variant.Outlined" class="rz-my-4">
    <RadzenStack Orientation="Orientation.Horizontal" Gap="0.75rem" AlignItems="AlignItems.Center" Wrap="FlexWrap.Wrap">
        <RadzenText Text="Rows:" />
        <RadzenSelectBar @bind-Value="scope" TValue="DataGridExportScope" Size="ButtonSize.Small">
            <Items>
                <RadzenSelectBarItem Text="Current page" Value="DataGridExportScope.CurrentPage" />
                <RadzenSelectBarItem Text="All" Value="DataGridExportScope.All" />
            </Items>
        </RadzenSelectBar>
        <RadzenCheckBox @bind-Value="useTheme" Name="useTheme" />
        <RadzenLabel Text="Use theme" Component="useTheme" />
        <RadzenButton Text="Export Excel" Icon="grid_on" ButtonStyle="ButtonStyle.Success" Click="ExportExcel" />
        <RadzenButton Text="Export CSV" Icon="description" ButtonStyle="ButtonStyle.Secondary" Click="ExportCsv" />
    </RadzenStack>
</RadzenCard>

<RadzenDataGrid @ref="grid" Data="orderDetails" TItem="OrderDetail" AllowPaging="true" PageSize="10"
                AllowSorting="true" AllowFiltering="true" GridLines="Radzen.DataGridGridLines.Both">
    <Columns>
        <RadzenDataGridColumn Property="OrderID" Title="Order ID" Width="100px" />
        <RadzenDataGridColumn Property="Order.OrderDate" Title="Order Date" FormatString="{0:d}" Width="130px" />
        <RadzenDataGridColumn Property="Product.ProductName" Title="Product" Width="240px" />
        <RadzenDataGridColumn Property="UnitPrice" Title="Unit Price" FormatString="{0:C2}" TextAlign="TextAlign.Right" Width="130px" />
        <RadzenDataGridColumn Property="Quantity" Title="Quantity" TextAlign="TextAlign.Right" Width="110px" />
        <RadzenDataGridColumn Property="Discount" Title="Discount" FormatString="{0:P0}" TextAlign="TextAlign.Right" Width="110px" />
    </Columns>
</RadzenDataGrid>

@code {
    RadzenDataGrid<OrderDetail> grid;
    List<OrderDetail> orderDetails = new();
    DataGridExportScope scope = DataGridExportScope.CurrentPage;
    bool useTheme = true;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        orderDetails = await dbContext.OrderDetails.Include(detail => detail.Order).Include(detail => detail.Product).ToListAsync();
    }

    Task ExportExcel()
    {
        return grid.ExportToExcelAsync("orders.xlsx", new DataGridExcelExportOptions { Scope = scope, Title = "Northwind order details", UseTheme = useTheme });
    }

    Task ExportCsv()
    {
        return grid.ExportToCsvAsync("orders.csv", new DataGridCsvExportOptions { Scope = scope });
    }
}
```


### LoadData export

This grid loads one page at a time. Exporting all rows requests the filtered and sorted data in chunks, reports progress, and restores the visible page when done.

```razor
@inherits DbContextPage

<RadzenStack Orientation="Orientation.Horizontal" Gap="0.75rem" AlignItems="AlignItems.Center" Wrap="FlexWrap.Wrap" class="rz-mb-4">
    <RadzenText Text="Rows:" />
    <RadzenSelectBar @bind-Value="scope" TValue="DataGridExportScope" Size="ButtonSize.Small">
        <Items>
            <RadzenSelectBarItem Text="Current page" Value="DataGridExportScope.CurrentPage" />
            <RadzenSelectBarItem Text="All" Value="DataGridExportScope.All" />
        </Items>
    </RadzenSelectBar>
    <RadzenCheckBox @bind-Value="useTheme" Name="loadDataUseTheme" />
    <RadzenLabel Text="Use theme" Component="loadDataUseTheme" />
    <RadzenButton Text="Export Excel" Icon="grid_on" ButtonStyle="ButtonStyle.Success" Disabled="exporting" Click="@(() => Export("excel"))" />
    <RadzenButton Text="Export CSV" Icon="description" ButtonStyle="ButtonStyle.Secondary" Disabled="exporting" Click="@(() => Export("csv"))" />
    @if (exporting)
    {
        <RadzenProgressBar Value="progressValue" ShowValue="true" Style="width: 260px" AriaLabel="Export progress" />
        <RadzenText Text="@($"{loaded} of {total} rows")" />
    }
</RadzenStack>

<RadzenDataGrid @ref="grid" Data="orderDetails" TItem="OrderDetail" Count="count" LoadData="LoadData"
                IsLoading="isLoading" AllowPaging="true" PageSize="10" AllowSorting="true" AllowFiltering="true">
    <Columns>
        <RadzenDataGridColumn Property="OrderID" Title="Order ID" Width="100px" />
        <RadzenDataGridColumn Property="Product.ProductName" Title="Product" Width="260px" />
        <RadzenDataGridColumn Property="UnitPrice" Title="Unit Price" FormatString="{0:C2}" TextAlign="TextAlign.Right" />
        <RadzenDataGridColumn Property="Quantity" Title="Quantity" TextAlign="TextAlign.Right" />
    </Columns>
</RadzenDataGrid>

@code {
    RadzenDataGrid<OrderDetail> grid;
    IEnumerable<OrderDetail> orderDetails;
    int count;
    int loaded;
    int total;
    bool isLoading;
    bool exporting;
    DataGridExportScope scope = DataGridExportScope.All;
    bool useTheme = true;

    double progressValue => total > 0 ? Math.Round(loaded * 100d / total) : 0;

    async Task LoadData(LoadDataArgs args)
    {
        isLoading = true;
        await Task.Yield();
        var query = dbContext.OrderDetails.Include(detail => detail.Order).Include(detail => detail.Product).AsQueryable();
        if (!string.IsNullOrEmpty(args.Filter))
        {
            query = query.Where(grid.ColumnsCollection);
        }
        if (!string.IsNullOrEmpty(args.OrderBy))
        {
            query = query.OrderBy(args.OrderBy);
        }
        count = query.Count();
        orderDetails = query.Skip(args.Skip ?? 0).Take(args.Top ?? 10).ToList();
        isLoading = false;
    }

    async Task Export(string format)
    {
        exporting = true;
        loaded = 0;
        total = count;
        try
        {
            var fileName = scope == DataGridExportScope.All ? "all-orders" : "orders";
            if (format == "excel")
            {
                await grid.ExportToExcelAsync($"{fileName}.xlsx", new DataGridExcelExportOptions
                {
                    Scope = scope,
                    ChunkSize = 25,
                    Title = "Northwind order details",
                    UseTheme = useTheme,
                    Progress = OnProgress
                });
            }
            else
            {
                await grid.ExportToCsvAsync($"{fileName}.csv", new DataGridCsvExportOptions
                {
                    Scope = scope,
                    ChunkSize = 25,
                    Progress = OnProgress
                });
            }
        }
        finally
        {
            exporting = false;
        }
    }

    void OnProgress(DataGridExportProgress value)
    {
        loaded = value.Loaded;
        total = value.Total;
        _ = InvokeAsync(StateHasChanged);
    }
}
```


### Customization

The Total column has no Property; it renders a template on screen and exports through `ExportValue`, with `FormatString` applied to the returned value. `ToWorkbookAsync` returns the workbook before it is saved so you can customize it with the full spreadsheet API - the customized download appends a totals row with a SUM formula.

```razor
@inherits DbContextPage

<RadzenStack Orientation="Orientation.Horizontal" Gap="0.75rem" class="rz-mb-4">
    <RadzenButton Text="Export Excel" Icon="grid_on" ButtonStyle="ButtonStyle.Success" Click="@(() => grid.ExportToExcelAsync("order-totals.xlsx", new DataGridExcelExportOptions { Scope = DataGridExportScope.All, Title = "Order totals" }))" />
    <RadzenButton Text="Download customized Excel" Icon="edit_document" ButtonStyle="ButtonStyle.Secondary" Click="ExportCustomExcel" />
</RadzenStack>

<RadzenDataGrid @ref="grid" Data="orderDetails" TItem="OrderDetail" AllowPaging="true" PageSize="5">
    <Columns>
        <RadzenDataGridColumn Property="Product.ProductName" Title="Product" />
        <RadzenDataGridColumn Property="Quantity" Title="Quantity" TextAlign="TextAlign.Right" />
        <RadzenDataGridColumn Property="UnitPrice" Title="Unit Price" FormatString="{0:C2}" TextAlign="TextAlign.Right" />
        <RadzenDataGridColumn Title="Total" TextAlign="TextAlign.Right" FormatString="{0:C2}" ExportValue="@(detail => Total(detail))">
            <Template Context="detail">@string.Format("{0:C2}", Total(detail))</Template>
        </RadzenDataGridColumn>
    </Columns>
</RadzenDataGrid>

@code {
    RadzenDataGrid<OrderDetail> grid;
    List<OrderDetail> orderDetails = new();

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        orderDetails = await dbContext.OrderDetails.Include(detail => detail.Product).ToListAsync();
    }

    static double Total(OrderDetail detail) => (detail.UnitPrice ?? 0) * (detail.Quantity ?? 0) * (1 - (detail.Discount ?? 0));

    async Task ExportCustomExcel()
    {
        var workbook = await grid.ToWorkbookAsync(new DataGridExcelExportOptions
        {
            Scope = DataGridExportScope.All,
            Title = "Order totals"
        });

        var sheet = workbook.Sheets[0];
        var lastDataRow = sheet.RowCount;
        var totalRow = lastDataRow + 1;
        sheet.Rows.Count = totalRow + 1;

        sheet.Cells[totalRow, 0].Value = "Grand total";
        sheet.Cells[totalRow, 0].Format.Bold = true;
        sheet.Cells[totalRow, 3].Formula = $"=SUM(D2:D{lastDataRow})";
        sheet.Cells[totalRow, 3].Format.Bold = true;
        sheet.Cells[totalRow, 3].Format.NumberFormat = sheet.Cells[1, 3].Format.NumberFormat;

        using var stream = new MemoryStream();
        workbook.SaveToStream(stream);
        stream.Position = 0;
        using var streamRef = new DotNetStreamReference(stream);
        await JSRuntime.InvokeVoidAsync("Radzen.downloadFile", "order-totals.xlsx", streamRef, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }
}
```
