使用IRONXL

如何在Blazor中导出到CSV

雷根·彭
雷根·彭
2023年五月23日
更新 2024年三月31日
分享:

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

IronXL 简介

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

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

将 Excel 文件转换为 CSV 的步骤

设置您的 Blazor 项目

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

一旦创建项目,打开Pages 文件夹并找到Index.razor文件。这是添加Blazor组件并编写代码以处理文件上传和转换的地方。

安装 IronXL

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

Install-Package IronXL.Excel

此命令将在 Blazor 项目中安装 IronXL 库。 现在您已经准备好开始编写代码了!

创建文件上传组件

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

@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>
$vbLabelText   $csharpLabel

这段代码设置了文件上传组件,包括一个按钮和一个显示文件转换状态的消息区。 InputFile组件上的accept属性指定接受的文件格式。

编写文件转换代码

现在,让我们来编写处理文件上传和转换的代码。 将结合使用 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
$vbLabelText   $csharpLabel

此代码定义了一个名为OnInputFileChange的私有方法,当使用InputFile组件上传Excel电子表格时,该方法将被触发; Excel 可以是 XLS 或 XLSX 格式。 代码读取上传的基本Excel文件,将其加载到WorkBook对象中,然后将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
$vbLabelText   $csharpLabel

让我们进一步分解代码:

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

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

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

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

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

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

  7. WorkBook对象的SaveAsCsv方法用于将工作簿保存为具有指定输出文件名的CSV文件。

  8. 如果转换成功,则会显示一条信息,说明转换已经完成。 如果出现错误,请捕捉异常并显示错误信息。

测试应用程序

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

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

运行Blazor应用程序

单击按钮,选择要上传的 Excel 文件。 接受的文件格式在InputFile组件的accept属性中列出。

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

选择一个Excel文件

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

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

转换状态

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

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

输出Excel文件

结论

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

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

IronXL 提供免费试用,让您在购买前测试其功能和能力。 试用期结束后,IronXL 的许可证起价为$749。

雷根·彭
软件工程师
Regan毕业于雷丁大学,拥有电子工程学士学位。在加入Iron Software之前,他的前工作职位要求他专注于单一任务;他在Iron Software最喜欢的是能进行多种工作,无论是增加销售价值、技术支持、产品开发还是营销。他喜欢了解开发人员如何使用Iron Software的库,并利用这些知识不断改进文档和开发产品。
< 前一页
如何在C#中将Excel转换为Datagridview
下一步 >
如何在C#中将Excel转换为数据表