How to Export to CSV in Blazor

Today, we're diving into how to use Blazor and IronXL to convert an Excel file to CSV format. By the end of this tutorial, you'll be able to create a basic Blazor application that exports Excel data in various formats, including CSV.

Introduction to IronXL

IronXL is a powerful .NET Excel library designed to work with Excel files in a wide range of formats, including XLS, XLSX, XLSM, XLTX, and CSV. It allows developers to read, write, and manipulate Excel data programmatically without the need for Microsoft Office or Excel Interop.

With IronXL, you can create, load, and save Excel workbooks, as well as read and write data to individual cells or ranges. It also supports advanced features such as formatting, formulas, charts, and pivot tables. IronXL is compatible with various .NET frameworks and can be used with popular languages like C# and VB.NET.

Steps to Convert Excel File to CSV

Setting Up Your Blazor Project

To get started, you'll need to create a new Blazor Server project. Open Visual Studio, create a new project and select the "Blazor Server App" template. Name your project, and click "Create."

Once your project is created, open the Pages folder and locate the Index.razor file. This is where we'll be adding our Blazor components and code to handle file uploads and conversions.

Installing IronXL

Before we can start writing code, we need to install the IronXL library. Open the Package Manager Console in Visual Studio and run the following command:

Install-Package IronXL.Excel

This command will install the IronXL library in your Blazor project. Now you're ready to start writing code!

Creating the File Upload Component

First, we'll create a basic file upload component that allows users to upload an existing Excel file. We'll be using the InputFile component from the Microsoft.AspNetCore.Components.Forms namespace. Add the following code to your Index.razor file, below the "@page "/" line:

@using Microsoft.AspNetCore.Components.Forms
@using IronXL
@using System.IO
@using System.Threading.Tasks

<div class="container">
    <h3>File Upload</h3>

    <InputFile class="button" OnChange="@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" />
    <h3>Selected File: @originalFileName</h3>
    <h3 style="color:bisque">Is File converted: <span>@message</span></h3>
</div>
@using Microsoft.AspNetCore.Components.Forms
@using IronXL
@using System.IO
@using System.Threading.Tasks

<div class="container">
    <h3>File Upload</h3>

    <InputFile class="button" OnChange="@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" />
    <h3>Selected File: @originalFileName</h3>
    <h3 style="color:bisque">Is File converted: <span>@message</span></h3>
</div>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@using Microsoft.AspNetCore.Components.Forms @using IronXL @using System.IO @using System.Threading.Tasks <div class="container"> <h3> File Upload</h3> <InputFile class="button" OnChange="@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" /> <h3> Selected File: @originalFileName</h3> <h3 style="color:bisque"> @Is File converted: <span> @message</span></h3> </div>
VB   C#

This code sets up the file upload component, complete with a button and a message area to display the status of the file conversion. The accept attribute on the InputFile component specifies the accepted file formats.

Writing the File Conversion Code

Now, let's write the code that handles the file upload and conversion. We'll be using a combination of IronXL, Blazor, and C# to accomplish this task. You can use IronXL to convert a CSV to an Excel file.

Add the following code to your Index.razor file, below the div element you added earlier.

@code {
    private string originalFileName;
    private string message = "";

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        var file = e.File;
        originalFileName = file.Name;

        try
        {
            // Read the uploaded file into a memory stream
            using var memoryStream = new MemoryStream();
            await file.OpenReadStream().CopyToAsync(memoryStream);

            // Load the workbook using IronXL
            WorkBook workBook = WorkBook.Load(memoryStream);

            // Save the workbook as a CSV file
            string outputPath = "sample.csv";
            workBook.SaveAsCsv(outputPath);

            message = "Conversion completed!";
        }
        catch (Exception ex)
        {
            message = $"An error occurred: {ex.Message}";
        }
    }
}
@code {
    private string originalFileName;
    private string message = "";

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        var file = e.File;
        originalFileName = file.Name;

        try
        {
            // Read the uploaded file into a memory stream
            using var memoryStream = new MemoryStream();
            await file.OpenReadStream().CopyToAsync(memoryStream);

            // Load the workbook using IronXL
            WorkBook workBook = WorkBook.Load(memoryStream);

            // Save the workbook as a CSV file
            string outputPath = "sample.csv";
            workBook.SaveAsCsv(outputPath);

            message = "Conversion completed!";
        }
        catch (Exception ex)
        {
            message = $"An error occurred: {ex.Message}";
        }
    }
}
code
If True Then
	private String originalFileName
	private String message = ""

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	private async Task OnInputFileChange(InputFileChangeEventArgs e)
'	{
'		var file = e.File;
'		originalFileName = file.Name;
'
'		try
'		{
'			' Read the uploaded file into a memory stream
'			var memoryStream = New MemoryStream();
'			await file.OpenReadStream().CopyToAsync(memoryStream);
'
'			' Load the workbook using IronXL
'			WorkBook workBook = WorkBook.Load(memoryStream);
'
'			' Save the workbook as a CSV file
'			string outputPath = "sample.csv";
'			workBook.SaveAsCsv(outputPath);
'
'			message = "Conversion completed!";
'		}
'		catch (Exception ex)
'		{
'			message = string.Format("An error occurred: {0}", ex.Message);
'		}
'	}
End If
VB   C#

This code defines a private method called OnInputFileChange, which will be triggered when an Excel spreadsheet is uploaded using the InputFile component; Excel can be in XLS or XLSX format. The code reads the uploaded basic Excel file, loads it into a WorkBook object, and then saves the WorkBook as a CSV file. The status of the conversion is displayed in the message area on the page.

Code Breakdown

First, look at the complete code:

@page "/"
@using Microsoft.AspNetCore.Components.Forms
@using IronXL
@using System.IO
@using System.Threading.Tasks

<style>
    body{
        background-color: skyblue
    }
    .container {
        max-width: 800px;
        margin: 0 auto;
        font-family: Arial, sans-serif;
    }

    h3 {
        margin-top: 30px;
        font-size: 30px;
        margin-bottom: 30px;
    }

    .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 15px 0;
        cursor: pointer;
    }
    span{
        font-size: 20px;
    }
</style>

<div class="container">
    <h3>File Upload</h3>

    <InputFile class="button" OnChange="@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" />
    <h3>Selected File: @originalFileName</h3>
    <h3 style="color:bisque">Is File converted: <span>@message</span></h3>
</div>

@code {
    private string originalFileName;
    private string message = "";

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        var file = e.File;
        originalFileName = file.Name;

        try
        {
            // Read the uploaded file into a memory stream
            using var memoryStream = new MemoryStream();
            await file.OpenReadStream().CopyToAsync(memoryStream);

            // Load the workbook using IronXL
            WorkBook workBook = WorkBook.Load(memoryStream);

            // Save the workbook as a CSV file
            string outputPath = "sample.csv";
            workBook.SaveAsCsv(outputPath);

            message = "Conversion completed!";
        }
        catch (Exception ex)
        {
            message = $"An error occurred: {ex.Message}";
        }
    }
}
@page "/"
@using Microsoft.AspNetCore.Components.Forms
@using IronXL
@using System.IO
@using System.Threading.Tasks

<style>
    body{
        background-color: skyblue
    }
    .container {
        max-width: 800px;
        margin: 0 auto;
        font-family: Arial, sans-serif;
    }

    h3 {
        margin-top: 30px;
        font-size: 30px;
        margin-bottom: 30px;
    }

    .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 15px 0;
        cursor: pointer;
    }
    span{
        font-size: 20px;
    }
</style>

<div class="container">
    <h3>File Upload</h3>

    <InputFile class="button" OnChange="@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" />
    <h3>Selected File: @originalFileName</h3>
    <h3 style="color:bisque">Is File converted: <span>@message</span></h3>
</div>

@code {
    private string originalFileName;
    private string message = "";

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {
        var file = e.File;
        originalFileName = file.Name;

        try
        {
            // Read the uploaded file into a memory stream
            using var memoryStream = new MemoryStream();
            await file.OpenReadStream().CopyToAsync(memoryStream);

            // Load the workbook using IronXL
            WorkBook workBook = WorkBook.Load(memoryStream);

            // Save the workbook as a CSV file
            string outputPath = "sample.csv";
            workBook.SaveAsCsv(outputPath);

            message = "Conversion completed!";
        }
        catch (Exception ex)
        {
            message = $"An error occurred: {ex.Message}";
        }
    }
}
page "/" [using] Microsoft.AspNetCore.Components.Forms [using] IronXL [using] System.IO [using] ReadOnly Property body() As System.Threading.Tasks(Of style)
		background-color: skyblue
End Property
	.container
	If True Then
		max-width: 800px
		margin:
		0 auto
		font-family: Arial, sans-serif
	End If

	h3
	If True Then
		margin-top: 30px
		font-size: 30px
		margin-bottom: 30px
	End If

	.button
	If True Then
		background-color: #4CAF50
		border:
		none
		color:
		white
		padding:
		15px 32px
		text-align: center
		text-decoration: none
		display:
		inline-block
		font-size: 16px
		margin:
		15px 0
		cursor:
		pointer
	End If
	span
	If True Then
		font-size: 20px
	End If
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: </style> <div class="container"> <h3> File Upload</h3> <InputFile class="button" OnChange="@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" /> <h3> Selected File: originalFileName</h3> <h3 style="color:bisque"> @Is File converted: <span> message</span></h3> </div> @code
".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" /> (Of h3) Selected File: originalFileName</h3> <h3 style="color:bisque"> [Is] File converted: (Of span) message</span></h3> </div> code
If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: </style> <div class="container"> <h3> File Upload</h3> <InputFile class="button" OnChange="@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" /> <h3> Selected File: originalFileName</h3> <h3 style
"@OnInputFileChange" accept=".xls,.xlsx,.xlsm,.xltx,.csv,.tsv" /> (Of h3) Selected File: originalFileName</h3> <h3 style
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: </style> <div class="container"> <h3> File Upload</h3> <InputFile class="button" OnChange="@OnInputFileChange" accept
"button" OnChange="@OnInputFileChange" accept
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: </style> <div class="container"> <h3> File Upload</h3> <InputFile class="button" OnChange
"container"> (Of h3) File Upload</h3> <InputFile class="button" OnChange
</style> <div class="container"> (Of h3) File Upload</h3> <InputFile class
	private String originalFileName
	private String message = ""

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	private async Task OnInputFileChange(InputFileChangeEventArgs e)
'	{
'		var file = e.File;
'		originalFileName = file.Name;
'
'		try
'		{
'			' Read the uploaded file into a memory stream
'			var memoryStream = New MemoryStream();
'			await file.OpenReadStream().CopyToAsync(memoryStream);
'
'			' Load the workbook using IronXL
'			WorkBook workBook = WorkBook.Load(memoryStream);
'
'			' Save the workbook as a CSV file
'			string outputPath = "sample.csv";
'			workBook.SaveAsCsv(outputPath);
'
'			message = "Conversion completed!";
'		}
'		catch (Exception ex)
'		{
'			message = string.Format("An error occurred: {0}", ex.Message);
'		}
'	}
End If
VB   C#

Let's break down the code further:

  1. When a file is uploaded, the OnInputFileChange method is triggered, and a InputFileChangeEventArgs object is passed to it. This object contains information about the uploaded file, such as its name and size.
  2. We store the original file name in a variable called originalFileName, so we can display it on the page.
  3. Inside a try-catch block, we first create a new MemoryStream object to read the uploaded file's contents. The using statement ensures that the memory stream is properly disposed of once it's no longer needed.
  4. We use the await keyword to asynchronously copy the contents of the uploaded file into the memory stream. This ensures that our application remains responsive while reading the file.
  5. Next, we use IronXL's WorkBook.Load method to load the contents of the memory stream into a WorkBook object. This object represents the entire Excel workbook, including its sheets, cells, and data.
  6. We then specify an output file name for the converted CSV file. In this case, we're using the name "sample.csv."
  7. We use the SaveAsCsv method of the WorkBook object to save the workbook as a CSV file with the specified output file name.
  8. If the conversion is successful, we display a message indicating that the conversion has been completed. If an error occurs, we catch the exception and display an error message.

Testing the Application

Now that our Blazor application is complete, it's time to test it! Press F5 to run your application in Visual Studio. Once the application is running, you should see a file upload button on the page.

How to Export to CSV in Blazor: Figure 1

Click the button, and select an Excel file to upload. The accepted file formats are listed in the accept attribute of the InputFile component.

How to Export to CSV in Blazor: Figure 2

After you've selected a file, the application will read the file, convert it to a CSV format using IronXL, and save the converted file with the specified output file name. You should see a message indicating the status of the conversion, as well as the original file name.

How to Export to CSV in Blazor: Figure 3

Congratulations! You've successfully built a Blazor application that can export Excel files to CSV format using IronXL. The following screenshot shows the output of the above program.

How to Export to CSV in Blazor: Figure 4

Conclusion

In this tutorial, we've explored how to build a Blazor application that can export Excel files to CSV format using IronXL. We've demonstrated how to create a file upload component, handle file uploads, and convert Excel files to CSV format using IronXL's powerful features.

By incorporating IronXL into your Blazor applications, you can easily handle a variety of Excel-related tasks, such as importing, manipulating, and exporting data. This opens up a wide range of possibilities for your projects and helps you provide a richer experience for your users. You can convert CSV to Excel in Blazor using the IronXL library.

IronXL offers a free trial, allowing you to test its features and capabilities before committing to a purchase. After the trial period, licenses for IronXL start at $749.