Skip to main content Skip to footer

How to Add a Blazor Excel XLSX Viewer to Your Web Application

Quick Start Guide
Tutorial Concept Learn how to integrate a JavaScript spreadsheet component with Blazor using JavaScript interop to import and display Excel XLSX files, navigate worksheets, and configure the imported workbook for read-only viewing in the browser.
What You Will Need
Controls Referenced SpreadJS | Top JavaScript Enterprise Spreadsheet Component

Excel workbooks are widely used to store and present financial data, reports, and other business information. In a web application, however, requiring users to download an XLSX file and open it in a separate desktop application can interrupt the workflow. By combining Blazor with SpreadJS, a JavaScript spreadsheet, you can display Excel workbooks directly in the browser and provide users with a familiar spreadsheet viewing experience.

In this tutorial, you’ll build a read-only Blazor Excel XLSX viewer using .NET 8, a JavaScript spreadsheet component, JavaScript interop, and Vite. Users will be able to select an XLSX file, import it into a SpreadJS workbook, navigate between worksheets, and view the workbook contents directly in the browser without modifying the original file.

Download the latest release of the industry-leading JS spreadsheet component, SpreadJS

Steps to Add a Blazor Excel XLSX Viewer to Web Apps

 Download a finished sample application to follow along


Step 1: Create a Blazor Project

Create a new Blazor Web App:

dotnet new blazor -n BlazorExcelViewer
cd BlazorExcelViewer

Install the JS spreadsheet packages, in this example we are using SpreadJS.

npm install @mescius/spread-sheets @mescius/spread-sheets-io
npm install vite --save-dev

Create vite.config.js:

import { defineConfig } from "vite";

export default defineConfig({
    build: {
        lib: {
            entry: "main.js",
            formats: ["iife"],
            name: "SpreadJSViewer",
            fileName: () => "spread.bundle.js"
        },
        outDir: "wwwroot/js",
        emptyOutDir: false
    }
});

Add the Vite build command to package.json:

"scripts": {
  "build": "vite build"
}

Created Blazor App | Excel Viewer Developer Tutorial


Step 2: Initialize the JavaScript Excel Viewer

Create main.js and import SpreadJS.

import * as GC from "@mescius/spread-sheets";
import "@mescius/spread-sheets-io";
import "@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css";

Then using the worbook constructor, initialize a JS spreadsheet instance.

let spread = null;

window.initializeExcelViewer = function (elementId) {
    const element = document.getElementById(elementId);
    if (!element) {
        return;
    }
    spread = new GC.Spread.Sheets.Workbook(element);
};

This creates a SpreadJS workbook inside the HTML element supplied by the Blazor component.


Step 3: Import an XLSX File

Add openExcelFile() to main.js:

window.openExcelFile = function (bytes) {
    const uint8Array = new Uint8Array(bytes);
    const blob = new Blob([uint8Array], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    const file = new File([blob], "document.xlsx");
    spread.import(
        file,
        function () {
            setWorkbookReadOnly();
        },
        function (error) {
            console.error("Error importing Excel file:", error);
        },
        {
            fileType: GC.Spread.Sheets.FileType.excel
        }
    );
};

The byte array received from Blazor is converted into a browser File and passed to the SpreadJS import() API to load the Excel workbook into the viewer.

To make the imported workbook read-only, add:

function setWorkbookReadOnly() {
    const sheetCount = spread.getSheetCount();
    for (let i = 0; i < sheetCount; i++) {
        const sheet = spread.getSheet(i);
        sheet.options.isProtected = true;
    }
}

This enables worksheet protection for every imported sheet, preventing users from editing locked cells while still allowing them to navigate the workbook.


Step 4: Add the Blazor File Picker

In Home.razor, create the viewer UI:

@page "/"
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.JSInterop
@inject IJSRuntime JS

<PageTitle>Excel XLSX Viewer</PageTitle>
<div class="viewer-page">
    <div class="viewer-header">
        <h1>Excel XLSX Viewer</h1>
        <p>Open and view Excel workbooks directly in your browser.</p>
    </div>
    <div class="viewer-toolbar">
        <label class="file-label">
            Choose XLSX File

            <InputFile
                OnChange="OpenExcelFile"
                accept=".xlsx"
                class="file-input" />
        </label>
        @if (!string.IsNullOrEmpty(fileName))
        {
            <span class="file-name">@fileName</span>
        }
    </div>
    <div id="excelViewer" class="excel-viewer"></div>
</div>

Initialize the JS spreadsheet workbook instance after the component renders:

private bool initialized;
private string? fileName;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JS.InvokeVoidAsync("initializeExcelViewer","excelViewer");
        initialized = true;
    }
}

Then read the selected XLSX file and send it to JavaScript:

private async Task OpenExcelFile(InputFileChangeEventArgs e)
{
    if (!initialized)
        return;
    var file = e.File;
    fileName = file.Name;
    const long maxFileSize = 50 * 1024 * 1024;
    await using var stream = file.OpenReadStream(maxFileSize);
    using var memoryStream = new MemoryStream();
    await stream.CopyToAsync(memoryStream);
    await JS.InvokeVoidAsync(
        "openExcelFile",
        memoryStream.ToArray());
}

Add a Blazor Excel File Viewer to Your Web Application | Dev Tutorial | Spreadsheet Solution


Step 5: Run the Viewer

Build the JavaScript bundle:

npm run build

Then run the Blazor application:

dotnet run

Click Choose XLSX File and select an Excel workbook. SpreadJS imports and displays the XLSX workbook directly in the web browser.

Import an Excel File into a Blazor Spreadsheet Viewer to Your Web Application | Dev Tutorial

 Download the finished sample application to see for yourself.


Conclusion

In this tutorial, you built a Blazor-based Excel XLSX viewer that loads workbooks directly in the browser using SpreadJS. You created a Vite bundle for the SpreadJS dependencies, initialized the workbook from Blazor through JavaScript interop, converted the selected XLSX file into a browser-compatible format, and imported it into the viewer.

You also configured the worksheets as read-only, added a Blazor file picker, and styled the viewer to provide a dedicated workspace for displaying Excel data. This approach provides a foundation for integrating Excel document viewing into Blazor applications while keeping the workbook accessible through a familiar spreadsheet interface.

Download the latest release of the industry-leading JS spreadsheet component, SpreadJS

Tags:

comments powered by Disqus