使用IRONXL

如何在 Blazor 中匯出為 CSV

里根普恩
里根普恩
2023年5月23日
已更新 2024年3月31日
分享:

今天,我們將深入探討如何使用 Blazor 和 IronXL 將 Excel 文件轉換為 CSV 格式。 到本教程結束時,您將能夠創建一個基本的Blazor應用程序,將Excel數據導出為包括CSV在內的各種格式。

IronXL 介紹

IronXL 是一款強大的.NET Excel 函式庫,旨在處理各種格式的 Excel 檔案,包括 XLS、XLSX、XLSM、XLTX 和 CSV。它允許開發人員以程式化方式讀取、撰寫和操作 Excel 資料,而無需安裝 Microsoft Office 或 Excel Interop。

使用 IronXL,您可以建立、載入及儲存Excel 工作簿,還可以讀取和寫入資料到單個儲存格或範圍。 它還支持進階功能,例如格式化公式圖表和樞紐分析表。 IronXL 相容於各種 .NET 框架,並且可以與 C# 和 VB.NET 等流行語言一起使用。

將 Excel 檔案轉換為 CSV 的步驟

設定您的 Blazor 專案

要開始,您需要建立一個新的 Blazor Server 專案。 打開 Visual Studio,創建一個新項目並選擇「Blazor 伺服器應用程式」範本。 命名您的專案,然後點擊「建立」。

一旦創建了專案,打開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 應用程式已完成,是時候進行測試了! 在 Visual Studio 中按 F5 來運行您的應用程式。 一旦應用程序運行起來,您應該會在頁面上看到一個文件上傳按鈕。

如何在 Blazor 中導出為 CSV,圖 1: 運行 Blazor 應用程序

運行Blazor應用程式

點擊按鈕,選擇一個 Excel 文件上傳。 可接受的檔案格式列在InputFile元件的accept屬性中。

如何在 Blazor 中匯出 CSV,圖 2:選擇 Excel 文件

選擇 Excel 檔案

選擇檔案後,應用程式將讀取該檔案,使用IronXL將其轉換為CSV格式,並將轉換後的檔案以指定的輸出檔案名稱儲存。 您應該會看到一則訊息顯示轉換的狀態以及原始檔案名稱。

如何在 Blazor 中匯出為 CSV,圖 3:轉換狀態

轉換狀態

恭喜! 您已成功構建了一個使用IronXL將Excel文件導出為CSV格式的Blazor應用程式。 以下螢幕截圖顯示了上述程式的輸出。

如何在 Blazor 中导出到 CSV,圖4:輸出 Excel 文件

輸出的 Excel 檔案

結論

本教程演示了如何使用IronXL建構一個Blazor應用程式,將Excel文件匯出為CSV格式。 我們展示了如何使用IronXL的強大功能,創建文件上傳組件、處理文件上傳以及將Excel文件轉換為CSV格式。

通過將 IronXL 集成到您的 Blazor 應用程式中,您可以輕鬆處理各種與 Excel 相關的任務,如匯入、操作和導出數據。 這為您的項目開啟了廣泛的可能性,幫助您為用戶提供更豐富的體驗。 您可以在 Blazor 中使用 IronXL 程式庫將 CSV 轉換為 Excel

IronXL 提供免費試用,讓您在購買前測試其功能和能力。 試用期結束後,IronXL的授權起價為$749。

里根普恩
軟體工程師
Regan 畢業於雷丁大學,擁有電子工程學士學位。在加入 Iron Software 之前,他的工作角色讓他專注於單一任務;而他在 Iron Software 工作中最喜歡的是他所能承擔的工作範圍,無論是增加銷售價值、技術支持、產品開發或市場營銷。他喜歡了解開發人員如何使用 Iron Software 庫,並利用這些知識不斷改進文檔和開發產品。
< 上一頁
如何在C#中將Excel轉換為Datagridview
下一個 >
如何在 C# 中將 Excel 轉換為 Datatable