Saltar al pie de página
USANDO IRONXL

Cómo exportar a CSV en 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:

  1. When a file is uploaded, the OnInputFileChange method is triggered, and an InputFileChangeEventArgs object is passed to it. This object contains information about the uploaded file, such as its name and size.
  2. Store the original file name in a variable called originalFileName to display it on the page.
  3. 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.
  4. 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.
  5. Next, the WorkBook.Load method is used 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. Then specify an output file name for the converted CSV file. In this case, we're using the name "sample.csv."
  7. The SaveAsCsv method of the WorkBook object is then used to save the workbook as a CSV file with the specified output file name.
  8. 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.

How to Export to CSV in Blazor, Figure 1: Run the Blazor application 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.

How to Export to CSV in Blazor, Figure 2: Select an Excel file 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.

How to Export to CSV in Blazor, Figure 3: Conversion status 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.

How to Export to CSV in Blazor, Figure 4: The output Excel file 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 $799.

Preguntas Frecuentes

¿Cómo puedo convertir un archivo de Excel a formato CSV en una aplicación Blazor?

Puedes convertir un archivo de Excel a formato CSV en una aplicación Blazor usando IronXL. Primero, configura un proyecto de Blazor Server, instala IronXL a través de la Consola del Administrador de Paquetes y crea un componente de carga de archivos con el componente `InputFile`. Luego, lee el archivo de Excel en un flujo de memoria, cárgalo en un objeto WorkBook usando IronXL y usa el método SaveAsCsv para exportar el archivo como CSV.

¿Cuál es el propósito de usar IronXL en aplicaciones Blazor?

IronXL se usa en aplicaciones Blazor para manejar datos de Excel sin la necesidad de Microsoft Office o Excel Interop. Permite a los desarrolladores leer, manipular y exportar datos de Excel de forma programática, habilitando funciones como la importación de datos, el formato y la conversión de archivos de Excel a formatos como CSV.

¿Puedo probar mi aplicación Blazor para convertir archivos de Excel a CSV?

Sí, puedes probar tu aplicación Blazor ejecutándola en Visual Studio. Usa el componente de carga de archivos para seleccionar un archivo de Excel. La aplicación convertirá el archivo seleccionado a CSV usando IronXL y proporcionará retroalimentación sobre el estado de la conversión.

¿Cuáles son los beneficios de usar IronXL sobre Excel Interop?

Usar IronXL sobre Excel Interop proporciona varios beneficios, incluyendo la habilidad de manipular archivos de Excel sin necesidad de tener Microsoft Office instalado, soporte para múltiples formatos de Excel (XLS, XLSX, CSV) y compatibilidad con aplicaciones .NET, mejorando el rendimiento y la facilidad de implementación.

¿Cómo instalo IronXL en mi proyecto Blazor?

Para instalar IronXL en tu proyecto Blazor, abre la Consola del Administrador de Paquetes en Visual Studio y ejecuta el comando: Install-Package IronXL.Excel. Esto instala la biblioteca, permitiéndote comenzar a trabajar con archivos de Excel de forma programática.

¿Qué formatos de archivo de Excel son compatibles con IronXL para la conversión en Blazor?

IronXL soporta una variedad de formatos de archivo de Excel para la conversión en Blazor, incluyendo .xls, .xlsx, .xlsm, .xltx y .csv, permitiendo un manejo flexible de los datos de Excel dentro de tus aplicaciones.

¿Cómo puedo crear un componente de carga de archivos en una aplicación Blazor?

Para crear un componente de carga de archivos en una aplicación Blazor, usa el componente `InputFile` del espacio de nombres Microsoft.AspNetCore.Components.Forms. Este componente permite a los usuarios cargar archivos, que luego pueden ser procesados usando IronXL para tareas como convertir Excel a CSV.

¿Hay una prueba gratuita disponible para IronXL?

Sí, IronXL ofrece una prueba gratuita que te permite explorar sus características y capacidades antes de realizar una compra. Después del período de prueba, puedes elegir entre varias opciones de licencia según las necesidades de tu proyecto.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más