Skip to main content Skip to footer

How to Export FlexGrid to Excel on the client-side?

The ComponentOne FlexGrid for Blazor, allows the option to export grids to Excel. We can utilize the grid.SaveAsync method to asyncronously save the FlexGrid to our desired Excel sheet.

Exporting Data | Blazor | ComponentOne

<FlexGrid @ref="grid" AutoSizeMode="GridAutoSizeMode.Both" ItemsSource="customersData" FrozenRows="1" AutoGenerateColumns="false">
    <FlexGridRows>
        <GridFilterRow IsVisible=@gridFilterRowIsVisible Placeholder="Search Text" />
    </FlexGridRows>
    <FlexGridColumns>
        <GridColumn Binding="Id" HeaderBackgroundColor="C1Color.FromARGB(200, 207, 209, 242)" />
        <GridColumn Binding="FirstName"  />
        <GridColumn Binding="LastName" />
        <GridColumn Binding="Country" HeaderHorizontalAlignment="C1HorizontalAlignment.Stretch" HorizontalAlignment="C1HorizontalAlignment.Right"/>
    </FlexGridColumns>
</FlexGrid>

<C1DataPager Source="@customersData"></C1DataPager>

@code {
    protected C1.Blazor.Grid.FlexGrid grid;
    List<Customer> customers;
    CustomerCollection customerCollecction;
    C1PagedDataCollection<Customer> customersData;

    protected override async Task OnInitializedAsync()
    {
        customerCollecction = new CustomerCollection();
        customersData = new C1PagedDataCollection<Customer>(customerCollecction) { PageSize = PageSize };
    }

    bool gridFilterRowIsVisible = true;
    public async Task Export()
    {
        var mimeType = new
        {
            Pdf = "application/pdf",
            Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        };
        try
        {
            byte[] fileContent = null;
            using (var stream = new MemoryStream())
            {
                customersData.PageSize = customerCollecction.Count;
                C1OrderedSet set = new C1OrderedSet(1, customerCollecction.Count); // to remove the Filter Row
                await grid.SaveAsync(stream, "Flexgrid Sheet", SaveFileFormat.Xlsx, new GridRowColRanges(set), null, GridHeadersVisibility.Column);
                customersData.PageSize = PageSize;
                fileContent = stream.ToArray();
            }

            await jsRuntime.InvokeVoidAsync("downloadFromByteArray", new
            {
                ByteArray = fileContent,
                FileName = "FlexGrid",
                ContentType = mimeType.GetType().GetProperty(SaveFileFormat.Xlsx.ToString()).GetValue(mimeType, null)
            });
        }
        catch (Exception e)
        {
            throw e;
        }
    }