Blazor | ComponentOne
Controls / FlexGrid / Exporting Data
In This Topic
    Exporting Data
    In This Topic

    FlexGrid allows you to export the grid data into supported file formats such as HTML, CSV, and TXT files. FlexGrid uses the Save method which accepts the file name or stream and file format as parameters to save the grid data at the server side. The file or stream can also be downloaded at the client side using the appropriate client script. The below image displays the FlexGrid with enabled support to export the data in supported file formats.

     

    Export

    To implement the Export feature in your FlexGrid application using code, you can follow the steps mentioned below.

    1. Define a method to export FlexGrid data to supported file formats and download the saved file at the client side.
      public void exportFlexGrid(string fileName,GridFileFormat format)
          {
              var _fileNameWithExtn = fileName+"." + format.ToString();
              var stream = new MemoryStream();
              grid.Save(stream, format);
              /* Uncomment following code line to download the saved file on client side */
              //JsRuntime.InvokeAsync<object>("saveAsFile", _fileNameWithExtn ,stream.ToArray()).AsTask();
          }   
      
    2. Write the following JavaScript function in the _Host.cshtml file to download the exported file at the client side.
      <script>
              function saveAsFile(filename, bytesBase64) {
                  var link = document.createElement('a');
                  link.download = filename;
                  link.href = "data:application/octet-stream;base64," + bytesBase64;
                  document.body.appendChild(link); // Needed for Firefox
                  link.click();
                  document.body.removeChild(link);
              }
          </script>
      
    3. Now, you have to invoke the Save method to export the FlexGrid data on a button click as shown in the image above.
          <button class="btn btn-primary" @onclick="@(e=> exportFlexGrid("FlexGrid",GridFileFormat.Html))">Html</button>
      

    Excel Export

    Excel export is supported on Server Side Blazor FlexGrid. It allows exporting the grid as displayed including all styles to Microsoft Excel. With this, FlexGrid features such as row\column freezing, grouping, merging, and cell styles are preserved while exporting the grid. Furthermore, it is also possible to export only selected ranges to be exported to excel.

    The following GIF showcases exporting FlexGrid to Microsoft Excel.

    Export

    To export FlexGrid to Microsoft Excel, use the following code. This example uses the sample created in Quick Start to display date & time, temperature and summary in the FlexGrid control. Here, we used the SaveAsync method to save the contents of FlexGrid in XLSX format.

    FetchData.razor
    Copy Code
    @using FlexGridIntro.Data
    @inject WeatherForecastService ForecastService
    @using System.IO;
    @inject IJSRuntime JsRuntime;
    <h1>Weather forecast</h1>
    
    <p>This component demonstrates fetching data from a service.</p>
    
    @if (forecasts == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
    <div>
        <button class="btn btn-primary" @onclick="@(e=>exportFlexGrid(SaveFileFormat.Xlsx))">XLSX</button>
    </div>
    <div>
        <FlexGrid @ref="grid" ItemsSource="forecasts"
                  AutoGenerateColumns="false"
                  Style="@(" max-height:500px;")">
            <FlexGridColumns>
                <GridColumn Binding="Date"></GridColumn>
                <GridColumn Binding="TemperatureC"></GridColumn>
                <GridColumn Binding="Summary"></GridColumn>
            </FlexGridColumns>
        </FlexGrid>
    </div>
    }
    
    @code {
        private WeatherForecast[] forecasts;
        FlexGrid grid;
    
        protected override async Task OnInitializedAsync()
        {
            forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
        }
        async void exportFlexGrid(SaveFileFormat fileFormat)
        {
            var mimeType = new
            {
                Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            };
            try
            {
                byte[] fileContent = null;
                using (var stream = new MemoryStream())
                {
                    await grid.SaveAsync(stream, "Flexgrid Sheet", fileFormat, null, null, GridHeadersVisibility.Column); // to show column header
                    fileContent = stream.ToArray();
                }
    
                await JsRuntime.InvokeVoidAsync("downloadFromByteArray", new
                {
                    ByteArray = fileContent,
                    FileName = "FlexGrid",
                    ContentType = mimeType.GetType().GetProperty(fileFormat.ToString()).GetValue(mimeType, null)
                });
            }
            catch (Exception e)
            {
    
            }
        }
    }