Codementor Events

How to export data to excel using Radzen and Blazor (.Net Core 3.1)

Published Nov 24, 2020
How to export data to excel using Radzen and Blazor (.Net Core 3.1)

Creating and exporting data to Excel file is one of the frequently used feature in web apps. We will learn about how to export data to excel in Blazor Server + Radzen project in this post.

Why I am writing this post? Few days back i was stragling with radzon export feature. When we tried to export data to excel file, it exported successfully but then application got crash with an exception. When i investigated it in-deep, there was an exception in browser console "Error: Circuit has been shut down due to error (Export)" which is known issue of Radzen so far! Even i was unable to show proper spinner for export function or any other operations on page. I need to just reload/refresh page to see it again.

Radzen team is trying solve the issue, but what i should do to provide facility to our clients with radzen/blazor project in meanwhile. So I am writing a short article with the solution about exporting excel in Radzen/Blazor without any exception and export files as many as you would like to do staying on same page.

Source Code link : Github
Download From Here

Creating a Radzen/Blazor Project

  1. Create new project
    1PNG.PNG

  2. Attach pre-defined / sample db for newly created project (create sample schema)
    2.PNG
    3.PNG
    4.PNG

click finish button and close data window. you will following pages

  1. Products
  2. Add Product
  3. Edit Product
    Products page has a fully functional gridview and export buttons for excel and csv files. We will try to run project and see the export features created by-default by radzen and will see the error/exception in browser console after one time export feature is done. But then you will see that you can not do anything on page untill a refresh is done on page.

5.PNG
6.PNG
7.PNG
8.PNG

Now as you can see, we received error in browser console which raises after we export data to excel or csv.

To resolve this issue, We need to open radzen solution into visual studio, i am using visual studio 2019. Here we will modify existing code to make it possible to resolve this issue and allow end user to export files as much as possible by staying on same page.

Customize Radzen Solution using Visual Studio 2019 (.Net Core 3.1)

  1. Open project in visual studio 2019
    9.PNG
    10.PNG

To resolve our issue we will start customization from ExportSampleDbController.cs
We will add following code to controller, so it will work like API controller.
This is the trick "api controller" and "httpClient", we will use these settings and libraries to extend the functionality for export.

using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ExportOperations.Data;

namespace ExportOperations
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public partial class ExportSampleDbController : ExportController

Now lets modify the SampleDbService, in your case use your service name which is calling this export method.

11.PNG

Firstly we will import HttpClient into our service and then will modify the code for excel export method. lets do it,

namespace ExportOperations
{
    public partial class SampleDbService
    {
        private readonly HttpClient httpClient;
        private readonly SampleDbContext context;
        private readonly NavigationManager navigationManager;

        public SampleDbService(HttpClient httpClient, SampleDbContext context, NavigationManager navigationManager)
        {
            this.httpClient = httpClient;
            this.context = context;
            this.navigationManager = navigationManager;
        }

Now we will modify ExportProductsToExcel method.
Here we are updating highlighted areas of method, we updated method return type to return byte[] array. We will get a byte arrray back to our blazor page where we will use it to write base64 response for export.

12.PNG

        public async Task<byte[]> ExportProductsToExcel(Query query = null, string fileName = null)
        {
            var url = query != null ? query.ToUrl($"api/ortSampleDb/ExportProductsToExcel/export/sampledb/products/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") : $"export/sampledb/products/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')";
            url = navigationManager.BaseUri + url;
            var response = await httpClient.GetAsync(url);
            var fileBytes = await response.Content.ReadAsByteArrayAsync();
            return fileBytes;
        }

Next we will modify "Products.razor.designer.cs" file to update this file there are two ways:
1. using visual studio designer.cs and meta json files
2. using radzen tool to update code

After you will be successfully update you code you will see following method code in designer.cs file

13.PNG

        protected async System.Threading.Tasks.Task Splitbutton0Click(RadzenSplitButtonItem args)
        {
            await Export();
        }

Next we need to add Export method into partial class in product.razor.cs
So Radzen tool should not remove it or update it while run from Radzen.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Radzen;
using Radzen.Blazor;
using Microsoft.JSInterop;

namespace ExportOperations.Pages
{
    public partial class ProductsComponent
    {
        public async Task Export()
        {
            byte[] response = await SampleDb.ExportProductsToExcel(new Query() { Filter = $@"{grid0.Query.Filter}", OrderBy = $"{grid0.Query.OrderBy}", Expand = "", Select = "Id,ProductName,ProductPrice,ProductPicture" }, $"Products");
            await JSRuntime.InvokeAsync<object>("saveAsFile", $"MyFile.xlsx", Convert.ToBase64String(response));
        }
    }
}

Our main focus is on two lines

byte[] response = await SampleDb.ExportProductsToExcel(new Query() { Filter = $@"{grid0.Query.Filter}", OrderBy = $"{grid0.Query.OrderBy}", Expand = "", Select = "Id,ProductName,ProductPrice,ProductPicture" }, $"Products");
                await JSRuntime.InvokeAsync<object>("saveAsFile", $"MyFile.xlsx", Convert.ToBase64String(response));

The Next step is to create "saveAsFile" method in a js file and include its reference in _host.cshtml file. Also remember to include _host.cshtml file into radzen ingnor list in app.json file.

Like this directly modifiying or using Radzen tool
14.PNG

the app.json file will look like this

{
  "dataSources": [
    "SampleDB"
  ],
  "generator": "@radzen/blazor-server",
  "https": false,
  "ignore": [
    "_Host.cshtml"
  ],
  "layouts": [
    "Login",
    "Main"
  ],
  "logo": "",
  "name": "ExportOperations",
  "navigation": [
    "Products"
  ],
  "pages": [
    "Products",
    "Add Product",
    "Edit Product"
  ],
  "port": 8000,
  "serverLang": "cs",
  "serverPort": 5000,
  "serverProject": true,
  "serverVersion": "3",
  "startPage": "Products",
  "theme": "default"
}

Add JS file
Lets say we are adding export.js file and add following code into it.

window.saveAsFile = function (fileName, byteBase64) {
    var link = this.document.createElement('a');
    link.download = fileName;
    link.href = "data:application/octet-stream;base64," + byteBase64;
    this.document.body.appendChild(link);
    link.click();
    this.document.body.removeChild(link);
}

Now add its reference to _Host.cshtml file, which looks like this

    <script src="_content/Radzen.Blazor/Radzen.Blazor.js"></script>
    <script src="_framework/blazor.server.js"></script>
    <script src="~/assets/js/export.js"></script>

Now I am updating products page to use code for export using Radzen Tool, this will update products.razor.designer.cs .

15.PNG
16.PNG

That's it, we resolve the issue and now are able to generate as many time as we want to use export button or feature. There will be no application crash now.

Happy Life with Radzen and Blazor.

Qaiser Mehmood,
Full Stack Developer | Solution Architect | Blazor | React | .Net Core
Tarigri Sharif, Daska Sialkot Pakistan.

Discover and read more posts from Qaiser Mehmood
get started
post commentsBe the first to share your opinion
Adem Çapan
2 years ago

hi thanks for this helpful article but I have a question where is your export controller
can you share the source code of export controller please

Qaiser Mehmood
2 years ago

https://github.com/qmmughal/blazor-radzen-exportdata
Please download full code here, you will find export controller in server folder.

Guy Tech
a year ago

Hi Qaiser Mehmood,

How to export some chart components of blazor radzen (as bar chart/chart column,…) to files as PDF or CSV or Excel? Please help me! Thanks!

Qaiser Mehmood
a year ago

Hi Guy Tech,
You need to follow pattern like export reports method works.
When you will pass chart datasource / data object to export method, it will work for you.

Thank you

Show more replies