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 the Blazor components are added and coded to handle file uploads and conversions.
Installing IronXL
Before starting to write code, it is necessary 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, create a basic file upload component that allows users to upload an existing Excel file. Then, the InputFile
component is added 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>
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. A combination of IronXL, Blazor, and C# will be used 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}";
}
}
}
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}";
}
}
}
Let's break down the code further:
- When a file is uploaded, the
OnInputFileChange
method is triggered, and anInputFileChangeEventArgs
object is passed to it. This object contains information about the uploaded file, such as its name and size. - Store the original file name in a variable called
originalFileName
to display it on the page. - Inside a try-catch block, 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. - Use the
await
keyword to asynchronously copy the contents of the uploaded file into the memory stream. This ensures that this application remains responsive while reading the file. - Next, the
WorkBook.Load
method is used to load the contents of the memory stream into aWorkBook
object. This object represents the entire Excel workbook, including its sheets, cells, and data. - Then specify an output file name for the converted CSV file. In this case, we're using the name "sample.csv."
- The
SaveAsCsv
method of theWorkBook
object is then used to save the workbook as a CSV file with the specified output file name. - If the conversion is successful, a message is displayed to indicate that the conversion has been completed. If an error occurs, catch the exception and display an error message.
Testing the Application
Now that the 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.
Run the Blazor application
Click the button, and select an Excel file to upload. The accepted file formats are listed in the accept attribute of the InputFile
component.
Select an Excel file
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.
Conversion status
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.
The output Excel file
Conclusion
This tutorial demonstrated 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.
Frequently Asked Questions
How can I convert an Excel file to CSV format in a Blazor application?
You can convert an Excel file to CSV format in a Blazor application by using IronXL. First, set up a Blazor Server project, install IronXL via the Package Manager Console, and create a file upload component with the `InputFile` component. Then, read the Excel file into a memory stream, load it into a WorkBook
object using IronXL, and use the SaveAsCsv
method to export the file as CSV.
What is the purpose of using IronXL in Blazor applications?
IronXL is used in Blazor applications to handle Excel data without the need for Microsoft Office or Excel Interop. It allows developers to read, manipulate, and export Excel data programmatically, enabling features like importing data, formatting, and converting Excel files to formats like CSV.
Can I test my Blazor application for converting Excel files to CSV?
Yes, you can test your Blazor application by running it in Visual Studio. Use the file upload component to select an Excel file. The application will convert the selected file to CSV using IronXL and provide feedback on the conversion status.
What are the benefits of using IronXL over Excel Interop?
Using IronXL over Excel Interop provides several benefits, including the ability to manipulate Excel files without needing Microsoft Office installed, support for multiple Excel formats (XLS, XLSX, CSV), and compatibility with .NET applications, enhancing performance and ease of deployment.
How do I install IronXL in my Blazor project?
To install IronXL in your Blazor project, open the Package Manager Console in Visual Studio and run the command: Install-Package IronXL.Excel
. This installs the library, allowing you to begin working with Excel files programmatically.
What Excel file formats are supported by IronXL for conversion in Blazor?
IronXL supports a variety of Excel file formats for conversion in Blazor, including .xls, .xlsx, .xlsm, .xltx, and .csv, allowing flexible handling of Excel data within your applications.
How can I create a file upload component in a Blazor application?
To create a file upload component in a Blazor application, use the `InputFile` component from the Microsoft.AspNetCore.Components.Forms namespace. This component enables users to upload files, which can then be processed using IronXL for tasks like converting Excel to CSV.
Is there a free trial available for IronXL?
Yes, IronXL offers a free trial that allows you to explore its features and capabilities before making a purchase. After the trial period, you can choose from various licensing options based on your project's needs.