Skip to main content Skip to footer

How to Import and Export CSV Files Using Blazor

Quick Start Guide
Tutorial Concept Learn how to integrate a JavaScript spreadsheet SDK with Blazor using JavaScript interop to import CSV files, edit and calculate data in an Excel-like spreadsheet, and export the updated data back to CSV.
What You Will Need
Controls Referenced

SpreadJS JavaScript Spreadsheet Component

CSV files remain one of the most common formats for transferring tabular data between applications. In business applications, users often need to upload CSV files, review and edit the data in a spreadsheet interface, perform calculations, and export the updated information back to a CSV file.

SpreadJS is designed and optimized to run in JavaScript applications, while Blazor is a .NET framework for building interactive web applications. Through JavaScript interop, SpreadJS can be integrated into Blazor projects to provide Excel-like spreadsheet functionality directly in the browser.

Download a finished sample application to follow along with the tutorial.

Steps to Import and Export CSV Files Using Blazor

  1. Create a Blazor Project
  2. Install SpreadJS Packages
  3. Project Structure
  4. Create the CSV File
  5. Create the SpreadJS Runtime
  6. Import CSV Data
  7. Export CSV
  8. Connect SpreadJS with Blazor
  9. Run the Application
  10. Review the Exported CSV File

JS Spreadsheet SDK for Importing and Exporting CSV files from Blazor Apps

Download the latest SpreadJS release today


1. Create a Blazor Project

Create a new Blazor application:

dotnet new blazor -n SpreadJSBlazorCsv
cd SpreadJSBlazorCsv

2. Install SpreadJS Packages

Initialize a npm project:

npm init -y

Install SpreadJS:

npm install @mescius/spread-sheets 

The project will now contain the SpreadJS libraries required for spreadsheet rendering and CSV processing.

3. Project Structure

After adding the SpreadJS integration, the project structure looks like:

SpreadJSBlazorCsv
│
├── Components
│   └── Pages
│       └── Home.razor
│
├── wwwroot
│   └── js
│       └── spread.bundle.js
│
├── src
│   └── main.js
│
├── package.json
├── Program.cs
└── appsettings.json

The generated JavaScript bundle is placed inside wwwroot so Blazor can load SpreadJS in the browser.

4. Create the CSV File

To test the application, create a file named:

products.csv

Add the following data:

Product,Quantity,Price,Total
Laptop,2,1200,2400
Monitor,3,250,750
Keyboard,5,80,400

This sample file contains product data that will be imported into the SpreadJS worksheet. The application is not limited to this file. Users can select other CSV files through the Blazor file input.

5. Create the SpreadJS Runtime

Inside main.js, import SpreadJS and its stylesheet and initialize the workbook:

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

let spread = null;
let importedRowCount = 0;
let importedColumnCount = 0;

window.createSpread = function (hostId) {
    const host = document.getElementById(hostId);
    spread = new GC.Spread.Sheets.Workbook(host);
};

6. Import CSV Data

The Blazor application reads the selected CSV file and passes its bytes to JavaScript using JavaScript Interop.

In main.js, decode the uploaded file and use SpreadJS setCsv() method to load the CSV content directly into the active worksheet:

window.importCsv = function (bytes) {
    const decoder = new TextDecoder("utf-8");
    const csvText = decoder.decode(new Uint8Array(bytes));
    const sheet = spread.getActiveSheet();
    const rowDelimiter = csvText.includes("\r\n")
        ? "\r\n"
        : "\n";
    const firstLine = csvText.split(/\r?\n/)[0] || "";
    const columnDelimiter =
        firstLine.includes(";") && !firstLine.includes(",")
            ? ";"
            : ",";
    const rows = csvText
        .trim()
        .split(/\r?\n/);
    importedRowCount = rows.length;
    importedColumnCount = firstLine
        .split(columnDelimiter)
        .length;
    sheet.setCsv(
        0,
        0,
        csvText,
        rowDelimiter,
        columnDelimiter
    );
};

The setCsv() method loads delimited text directly into the worksheet starting at row 0 and column 0. This example also detects whether the imported file uses a comma or semicolon as its column delimiter. The row and column counts are stored so that the application can export only the imported data range.

7. Export CSV

After reviewing or modifying the worksheet, use the SpreadJS getCsv() method to retrieve the worksheet data as CSV-formatted text.

Add the following function to main.js:

window.exportCsv = function () {
    const sheet = spread.getActiveSheet();
    if (importedRowCount === 0 || importedColumnCount === 0) {
        console.log("No CSV data has been imported.");
        return;
    }
    const csv = sheet.getCsv(
        0,
        0,
        importedRowCount,
        importedColumnCount,
        "\r\n",
        ";"
    );
    const blob = new Blob(
        ["\uFEFF" + csv],
        { type: "text/csv;charset=utf-8;" }
    );
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "export.csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
};

The getCsv() method retrieves the specified worksheet range as delimited text.

In this example, the exported file uses a semicolon as the column delimiter for compatibility with Excel configurations that use semicolons as their default list separator. The UTF-8 byte order mark (\uFEFF) is also added to help Excel recognize UTF-8 encoded text.

The browser then creates a blob, generates a temporary object URL, and downloads the data as export.csv.

8. Connect SpreadJS with Blazor

Create a Blazor component to host the spreadsheet and provide the CSV import and export controls.

@inject IJSRuntime JS
<div>
    <InputFile OnChange="ImportCsv"/>

    <button class="btn btn-primary"
            @onclick="ExportCsv">
        Export CSV
    </button>
</div>
<div id="spreadHost"
     style="width:100%;height:600px">
</div>

@code {

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if(firstRender)
        {
            await JS.InvokeVoidAsync(
                "createSpread",
                "spreadHost"
            );
        }
    }

    private async Task ImportCsv(InputFileChangeEventArgs e)
    {
        var file = e.File;
        using var stream = file.OpenReadStream();
        using var memory = new MemoryStream();
        await stream.CopyToAsync(memory);
        await JS.InvokeVoidAsync(
            "importCsv",
            memory.ToArray()
        );
    }
    private async Task ExportCsv()
    {
        await JS.InvokeVoidAsync(
            "exportCsv"
        );
    }
}

The InputFile component allows the user to select a CSV file.

Blazor reads the selected file into memory and passes the resulting byte array to the JavaScript importCsv() function through JavaScript Interop.

When the user clicks Export CSV, Blazor calls the JavaScript exportCsv() function, which retrieves the worksheet data and downloads it as a CSV file.

9. Run the Application

Build the SpreadJS bundle:

npm run build

Run the Blazor application:

dotnet run

Open the browser and upload:

products.csv

The CSV data will appear inside SpreadJS.

10. Review the Exported CSV File

After clicking Export CSV, a new file is generated:

export.csv

The exported file can be opened directly in any app that reads .csv files, such as Microsoft Excel.

Export CSV File from Blazor Application

Example output:

Product,Quantity,Price,Total
Laptop,2,1200,2400
Monitor,3,250,750
Keyboard,5,80,400

Example CSV File Screenshot | Exported from a Blazor Application

Conclusion

In this tutorial, we created a CSV import and export workflow using Blazor and SpreadJS. Blazor handles file selection and communicates with the browser through JavaScript Interop, while SpreadJS provides the spreadsheet interface and CSV processing functionality.

Using the SpreadJS setCsv() method allows CSV content to be loaded directly into a worksheet without manually assigning each value to individual cells. The getCsv() method provides the corresponding workflow for retrieving worksheet data as CSV-formatted text after users have reviewed or edited the spreadsheet.

By combining Blazor with SpreadJS, developers can build interactive spreadsheet-based web applications that allow users to import, work with, and export tabular data directly in the browser.

Tags:

comments powered by Disqus