Skip to main content Skip to footer

How to Import and Export Excel XLSX Using Blazor

Quick Start Guide
Tutorial Concept

Import/Export Excel XLSX in Blazor - Explore the functionality to add Excel documents to your Blazor applications using the IO functionality of SpreadJS spreadsheet components.

What You Will Need

SpreadJS

VS Code (and C# Dev Kit)

Blazor

Controls Referenced SpreadJS

Blazor is a relatively new framework for building an interactive client-side web UI with the power of .NET. A common use case is importing your existing Excel files to your Blazor application, presenting the spreadsheet data to your users, allowing any changes to be made, and then exporting that data back out to an Excel file or saving it to a database. SpreadJS is a very powerful and extensible JavaScript spreadsheet component that makes this process easy.

If you want to follow along with this tutorial, the download for the sample can be found here.

Below are the steps to use Blazor to import and export Excel files with SpreadJS:

  1. Create the Blazor Application
  2. Create the SpreadJS Component
  3. Add SpreadJS Excel Import and Export
  4. Add SpreadJS Component to Home Page

Ready to Get Started? Download SpreadJS Now!

Create the Blazor Application

Before we can put SpreadJS in a Blazor application, we must first create a Blazor component to contain SpreadJS. In this tutorial, we will use Visual Studio Code and SpreadJS v18. Part of this tutorial for creating the Blazor app comes from this Microsoft tutorial.

To get started, we need to make sure we have the .NET SDK, Visual Studio Code, and the C# Dev Kit installed. There is a WinGet file that can be used from the above tutorial to install all of these. Once those are installed, open up Visual Studio Code and make sure that the .NET SDK was installed properly by using the following command in a terminal:

dotnet

If the installation was successful, you should see the following in the terminal:

Installation

Now we are set up to create the app by opening the command palette in VS Code and by pressing CTRL + SHIFT + P.  You’ll want to type in “.NET” and select .NET: New Project…. Once that finishes, scroll down and select Blazor Web App. Enter a name for the project and the location:

Command Palette

Now you should have a project with the following folders and files:

Explorer

We need to test this program to make sure that it runs, so click on the Run and Debug button on the left-hand side of VS Code. Then, select C#: SpreadJS_Blazor [Default Configuration] (this is the same as the name of the project you specified earlier):

Run and Debug

This should automatically build and run the application in your default web browser:

Run application

Create SpreadJS Component

Now that we have created the project and ensured it runs properly, we need to add references to the SpreadJS libraries in the Components>App.razor file:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="@Assets["lib/bootstrap/dist/css/bootstrap.min.css"]" />
    <link rel="stylesheet" href="@Assets["app.css"]" />
    <link rel="stylesheet" href="@Assets["SpreadJS_Blazor.styles.css"]" />
    <link href="https://cdn.mescius.com/spreadjs/hosted/css/gc.spread.sheets.excel2013white.18.0.2.css" rel="stylesheet" type="text/css" />
    <ImportMap />
    <link rel="icon" type="image/png" href="favicon.png" />
    <HeadOutlet />
</head>

<body>
    <Routes />
    <script src="_framework/blazor.web.js"></script>
    <script src="./FileSaver.js"></script>
    <script type="text/javascript" src="https://cdn.mescius.com/spreadjs/hosted/scripts/gc.spread.sheets.all.18.0.2.min.js"></script>
<script src="https://cdn.mescius.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.io.18.0.2.min.js"></script>
</body>

</html>

Then, we need to create the razor component for SpreadJS. Navigate to the Pages folder and create two new files:

  • SpreadJS.razor
  • SpreadJS.razor.js

In the SpreadJS.razor file, we want to specify the HTML elements that are going to be on our page as well as some functions that will call our asynchronous JavaScript functions which we will define momentarily:

@page "/spreadjs"
@rendermode InteractiveServer
@inject IJSRuntime JS
@using Microsoft.JSInterop


<div @ref="host"></div>
<table>
    <tr>
        <td>
            <label>Sheet Index</label>
            <input @bind-value="@SheetIndex" />
        </td>
        <td>
            <label>Row Index</label>
            <input @bind-value="@Row" />
        </td>
        <td>
            <label>Column Index</label>
            <input @bind-value="@Column" />
        </td>
        <td>
            <label>Value</label>
            <input @bind-value="@Value" />
        </td>
    </tr>
    <tr>
        <td>
            <button @onclick="SetValue">Update Text</button>
        </td>
    </tr>
    <tr>
        <td>
            <input type="file" @ref="inputFileEle" />
        </td>
        <td>
            <button @onclick="ImportExcel">Import File</button>
        </td>
    </tr>
</table>

@code {
    [Parameter]
    public int SheetCount { get; set; }

    [Parameter]
    public string HostStyle { get; set; }

    public int SheetIndex { get; set; } = 0;

    public int Row { get; set; } = 0;

    public int Column { get; set; } = 0;

    public string Value { get; set; } = "";

    private IJSObjectReference? module;

    private ElementReference host;

    private ElementReference inputFileEle;

    public void SetValue()
    {
        module?.InvokeVoidAsync("setValue", [host, SheetIndex, Row, Row, Value]);
    }

    public void ImportExcel()
    {
        module?.InvokeVoidAsync("openExcel", [host, inputFileEle]);
    }
    
    public void ExportExcel() {
        module?.InvokeVoidAsync("saveExcel", [host]);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            module = await JS.InvokeAsync<IJSObjectReference>("import",
            "./Components/Pages/SpreadJS.razor.js");

            await module.InvokeVoidAsync("init", [host, new Dictionary<string, object>
            {
                { "sheetCount", SheetCount },
                { "hostStyle", HostStyle }
            }]);
        }
    }
}

Add SpreadJS Excel Import and Export

Now, we can define the JavaScript functions in the SpreadJS.razor.js file that will handle importing and exporting Excel files to and from SpreadJS.  This is mostly the same as our standard JavaScript code, but instead, we will add “export” in front of the functions:

export function init(host, config) {
    if (config.hostStyle) {
        var hostStyle = config.hostStyle;
        var styles = hostStyle.split(';');
        styles.forEach((styleStr) => {
            var style = styleStr.split(':');
            host.style[style[0]] = style[1];
        });
        delete config.hostStyle;
    }

    new GC.Spread.Sheets.Workbook(host, config);
}

export function setValue(host, sheetIndex, row, col, value) {
    let spread = GC.Spread.Sheets.findControl(host);
    if (spread) {
        let sheet = spread.getSheet(sheetIndex);
        sheet.setValue(row, col, value);
    }
}

export function openExcel(host, inputFile) {
    let spread = GC.Spread.Sheets.findControl(host);
    let file = inputFile.files[0];
    if (spread && file) {
        spread.import(file, () => {
            console.log("successfully");
        }, (message) => {
            alert(message);
        }, {
            fileType: GC.Spread.Sheets.FileType.excel
        });
    }
}

export function saveExcel(host) {
    let spread = GC.Spread.Sheets.findControl(host);
    let fileName = "export.xlsx";
    if (spread) {
        spread.export(function (blob) {
            // save blob to a file
            saveAs(blob, fileName);
         }, function (e) {
            console.log(e);
         }, {
            fileType: GC.Spread.Sheets.FileType.excel
         });
    }
}

Add SpreadJS Component to Home Page

Now that we have created the component that contains SpreadJS, we can add it to the home page so that it loads when we start the application. In the Home.razor file, add the following code:

@page "/"
@using Microsoft.JSInterop
@using SpreadJS_Blazor.Components.Pages

<PageTitle>Home</PageTitle>

<h1>Hello, SpreadJS!</h1>

<SpreadJS SheetCount="3" HostStyle="@HostStyle"></SpreadJS>

@code {
    private string HostStyle { get; set; } = "width:90wh;height:60vh;border: 1px solid darkgray";
}

Now, we are ready to run the application again. Click on the Run and Debug button again. This will start the application in a specific location:

Final application

This blog showed how to implement SpreadJS in your Blazor applications and leverage the power of .NET to import and export XLSX files. To try this and see what other amazing features SpreadJS has, download a trial today!

Learn more about this JavaScript Spreadsheet Component:

Ready to Get Started? Download SpreadJS Now!

Tags:

comments powered by Disqus