使用IRONXL

如何在 Blazor 中匯出為 CSV

已更新 2024年3月31日
分享:

今天,我們將探討如何使用Blazor和IronXL將Excel檔案轉換為CSV格式。在本教程的最後,您將能夠創建一個基本的Blazor應用程式,將Excel數據以包括CSV在內的多種格式導出。

IronXL介紹

IronXL是一款強大的 .NET Excel 函式庫 設計與 Excel 文件一起使用 多種格式,包括 XLS、XLSX、XLSM、XLTX 和 CSV。它允許開發人員在不需要 Microsoft Office 或 Excel Interop 的情況下,以程式方式讀取、編寫和操作 Excel 數據。

使用 IronXL,您可以建立、載入和儲存 Excel 工作簿以及讀寫至個別儲存格或範圍的數據。它還支持一些高級功能,例如 格式化, 公式, 圖表, 以及数据透视表。IronXL 兼容各种 .NET 框架,并可与 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 元件。將以下代碼新增到 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#

這段程式碼設置了檔案上傳元件,包含一個按鈕和一個訊息區域來顯示檔案轉換的狀態。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
VB   C#

此程式碼定義了一個名為 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
VB   C#

讓我們進一步拆解程式碼:

  1. 當文件被上傳時,會觸發 OnInputFileChange 方法,並將一個 InputFileChangeEventArgs 對象傳遞給它。這個對象包含關於上傳文件的信息,比如它的名稱和大小。

  2. 將原始檔名稱儲存在一個名為 originalFileName 的變數中,以便在頁面上顯示。

  3. 在 try-catch 區塊內,建立一個新的 MemoryStream 對象來讀取上傳文件的內容。using 語句確保記憶流在不再需要時能被正確釋放。

  4. 使用 await 關鍵字異步地將上傳文件的內容複製到記憶流中。這確保應用程式在讀取文件期間保持響應。

  5. 接下來 WorkBook.Load 方法用於將記憶體流的內容加載到 WorkBook 對象中。該對象表示整個 Excel 工作簿,包括其工作表、單元格和數據。

  6. 然後指定轉換後的 CSV 文件的輸出文件名。在這種情況下,我們使用名稱 "sample.csv"。

  7. The SaveAsCsv 然後使用 WorkBook 對象的方法將工作簿保存為具有指定輸出文件名的 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相關的任務,例如導入、操作和導出數據。這為您的項目開闢了一個廣闊的可能性範圍,並有助於為用戶提供更豐富的體驗。您可以 將 CSV 轉換為 Excel 在 Blazor 中使用 IronXL 函式庫。

IronXL 提供一個 免費試用在試用期內,您可以測試其功能和性能,然後再決定是否購買。試用期結束後,IronXL的許可證價格從 $749 起。

< 上一頁
如何在C#中將Excel轉換為Datagridview
下一個 >
如何在 C# 中將 Excel 轉換為 Datatable

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 1,023,839 查看許可證 >