使用IRONXL

如何在Blazor中导出到CSV

更新 2024年三月31日
分享:

今天,我们将深入探讨如何使用 Blazor 和 IronXL 将 Excel 文件转换为 CSV 格式。本教程结束时,您将能够创建一个基本的 Blazor 应用程序,以各种格式(包括 CSV)导出 Excel 数据。

IronXL 简介

IronXL 是一款功能强大的 .NET Excel 库 设计用于在 多种格式包括 XLS、XLSX、XLSM、XLTX 和 CSV。它允许开发人员以编程方式读取、写入和处理 Excel 数据,而无需 Microsoft Office 或 Excel Interop。

使用 IronXL,您可以创建、加载和保存 Excel 工作簿以及读取和写入单个单元格或范围的数据。它还支持以下高级功能 格式化, 公式, 图表以及数据透视表。IronXL 与各种 .NET 框架兼容,可用于 C# 和 VB.NET 等流行语言。

将 Excel 文件转换为 CSV 的步骤

设置您的 Blazor 项目

开始之前,您需要创建一个新的 Blazor 服务器项目。打开 Visual Studio,创建一个新项目,然后选择 "Blazor Server App "模板。为项目命名,然后点击 "创建"。

项目创建完成后,打开页面文件夹,找到Index.razor文件。这里添加了 Blazor 组件并进行了编码,以处理文件上传和转换。

安装 IronXL

在开始编写代码之前,有必要安装 IronXL 库。在 Visual Studio 中打开软件包管理器控制台,运行以下命令:

Install-Package IronXL.Excel

该命令将在 Blazor 项目中安装 IronXL 库。现在您可以开始编写代码了!

创建文件上传组件

首先,创建一个允许用户上传现有 Excel 文件的基本文件上传组件。然后,从 "Microsoft.AspNetCore.Components.Forms "命名空间中添加 "InputFile "组件。在Index.razor文件的"@page"/"行下面添加以下代码:

@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#

这段代码将设置文件上传组件,其中包括一个按钮和一个显示文件转换状态的信息区域。输入文件 "组件上的 "接受 "属性指定了可接受的文件格式。

编写文件转换代码

现在,让我们编写处理文件上传和转换的代码。我们将结合使用 IronXL、Blazor 和 C# 来完成这项任务。您可以使用 IronXL 将 CSV 转换为 Excel 文件.

将以下代码添加到 Index.razor 文件中,位于之前添加的 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}";
        }
    }
}
@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#

该代码定义了一个名为 "OnInputFileChange "的私有方法,当使用 "InputFile "组件上传 Excel 电子表格时将触发该方法;Excel 可以是 XLS 或 XLSX 格式。代码读取上传的基本 Excel 文件,将其加载到一个 工作簿 对象,然后将 "WorkBook "保存为 CSV 文件。转换的状态会显示在页面的消息区。

代码分解

首先,请看完整的代码:

@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#

让我们进一步分解代码:

1.上传文件时,会触发 OnInputFileChange 方法,并向其传递一个 InputFileChangeEventArgs 对象。该对象包含上传文件的相关信息,如文件名和大小。

2.在名为 originalFileName 的变量中存储原始文件名,以便在页面上显示。

3.在 try-catch 块中,创建一个新的 MemoryStream 对象来读取上传文件的内容。using 语句可确保内存流在不再需要时得到妥善处理。

4.使用 await 关键字异步地将上传文件的内容复制到内存流中。这将确保应用程序在读取文件时保持响应。

5.接下来,使用 工作簿载入 方法用于将内存流的内容加载到 "WorkBook "对象中。该对象代表整个 Excel 工作簿,包括工作表、单元格和数据。

6.然后为转换后的 CSV 文件指定一个输出文件名。在本例中,我们使用的文件名是 "sample.csv"。

7.文件名 保存为 Csv 方法将工作簿保存为 CSV 文件,并指定输出文件名。

8.如果转换成功,将显示一条消息,说明转换已完成。如果发生错误,则捕获异常并显示错误消息。

测试应用程序

现在 Blazor 应用程序已经完成,是时候进行测试了! 按 F5 键在 Visual Studio 中运行应用程序。程序运行后,页面上会出现一个文件上传按钮。

如何在 Blazor 中导出为 CSV,图 1:运行 Blazor 应用程序

运行Blazor应用程序

单击按钮,选择要上传的 Excel 文件。输入文件 "组件的接受属性中列出了可接受的文件格式。

如何在 Blazor 中导出为 CSV,图 2:选择 Excel 文件

选择一个 Excel 文件

选择文件后,应用程序将读取文件,使用 IronXL 将其转换为 CSV 格式,并以指定的输出文件名保存转换后的文件。你会看到一条显示转换状态和原始文件名的信息。

如何在 Blazor 中导出为 CSV,图 3:转换状态

转换状态

祝贺! 您已经成功创建了一个 Blazor 应用程序,它可以使用 IronXL 将 Excel 文件导出为 CSV 格式。下面的截图显示了上述程序的输出结果。

如何在 Blazor 中导出为 CSV,图 4:输出的 Excel 文件

输出 Excel 文件

结论

本教程演示了如何使用 IronXL 构建一个可将 Excel 文件导出为 CSV 格式的 Blazor 应用程序。我们演示了如何创建文件上传组件、处理文件上传以及使用 IronXL 的强大功能将 Excel 文件转换为 CSV 格式。

通过将 IronXL 集成到 Blazor 应用程序中,您可以轻松处理各种 Excel 相关任务,如导入、操作和导出数据。这将为您的项目带来更多可能性,并帮助您为用户提供更丰富的体验。您可以 将 CSV 转换为 Excel 在 Blazor 中使用 IronXL 库。

IronXL 提供了一个 免费试用在试用期结束后,IronXL 的许可证价格为"$liteLicense"。试用期过后,IronXL 的许可证起价为 $749。

< 前一页
如何在C#中将Excel转换为Datagridview
下一步 >
如何在C#中将Excel转换为数据表

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 988,189 查看许可证 >