在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
今天,我們將深入探討如何使用 Blazor 和 IronXL 將 Excel 文件轉換為 CSV 格式。 到本教程結束時,您將能夠創建一個基本的Blazor應用程序,將Excel數據導出為包括CSV在內的各種格式。
IronXL 是一款強大的.NET Excel 函式庫,旨在處理各種格式的 Excel 檔案,包括 XLS、XLSX、XLSM、XLTX 和 CSV。它允許開發人員以程式化方式讀取、撰寫和操作 Excel 資料,而無需安裝 Microsoft Office 或 Excel Interop。
使用 IronXL,您可以建立、載入及儲存Excel 工作簿,還可以讀取和寫入資料到單個儲存格或範圍。 它還支持進階功能,例如格式化、公式、圖表和樞紐分析表。 IronXL 相容於各種 .NET 框架,並且可以與 C# 和 VB.NET 等流行語言一起使用。
要開始,您需要建立一個新的 Blazor Server 專案。 打開 Visual Studio,創建一個新項目並選擇「Blazor 伺服器應用程式」範本。 命名您的專案,然後點擊「建立」。
一旦創建了專案,打開Pages 資料夾並找到Index.razor文件。這裡是加入和編寫 Blazor 元件以處理文件上傳和轉換的地方。
在開始撰寫程式碼之前,有必要安裝 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>
此程式碼設置了文件上傳元件,完整搭配按鈕及訊息區域以顯示文件轉換的狀態。 在 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
此程式碼定義了一個名為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
讓我們進一步分析這段代碼:
當檔案上傳時,將觸發OnInputFileChange
方法,並將InputFileChangeEventArgs
物件傳遞給它。 該物件包含有關上傳文件的信息,例如其名稱和大小。
將原始檔名儲存在一個名為originalFileName
的變數中,以便在頁面上顯示。
在 try-catch 區塊中,創建一個新的 MemoryStream
物件以讀取上傳檔案的內容。 using 語句確保記憶體流一旦不再需要時能被妥善處理。
使用 await
關鍵字以非同步方式將上傳文件的內容複製到記憶體流中。 這確保了應用程式在讀取文件時保持響應。
接下來,WorkBook.Load
方法用於將記憶體流的內容載入到 WorkBook
物件中。 此對象代表整個 Excel 工作簿,包括其工作表、單元格和數據。
然後指定轉換後的 CSV 檔案名稱。在這個例子中,我們使用名稱 "sample.csv"。
然後使用WorkBook
物件的SaveAsCsv
方法將工作簿保存為具有指定輸出檔名的CSV檔案。
現在 Blazor 應用程式已完成,是時候進行測試了! 在 Visual Studio 中按 F5 來運行您的應用程式。 一旦應用程序運行起來,您應該會在頁面上看到一個文件上傳按鈕。
運行Blazor應用程式
點擊按鈕,選擇一個 Excel 文件上傳。 可接受的檔案格式列在InputFile
元件的accept屬性中。
選擇 Excel 檔案
選擇檔案後,應用程式將讀取該檔案,使用IronXL將其轉換為CSV格式,並將轉換後的檔案以指定的輸出檔案名稱儲存。 您應該會看到一則訊息顯示轉換的狀態以及原始檔案名稱。
轉換狀態
恭喜! 您已成功構建了一個使用IronXL將Excel文件導出為CSV格式的Blazor應用程式。 以下螢幕截圖顯示了上述程式的輸出。
輸出的 Excel 檔案
本教程演示了如何使用IronXL建構一個Blazor應用程式,將Excel文件匯出為CSV格式。 我們展示了如何使用IronXL的強大功能,創建文件上傳組件、處理文件上傳以及將Excel文件轉換為CSV格式。
通過將 IronXL 集成到您的 Blazor 應用程式中,您可以輕鬆處理各種與 Excel 相關的任務,如匯入、操作和導出數據。 這為您的項目開啟了廣泛的可能性,幫助您為用戶提供更豐富的體驗。 您可以在 Blazor 中使用 IronXL 程式庫將 CSV 轉換為 Excel。
IronXL 提供免費試用,讓您在購買前測試其功能和能力。 試用期結束後,IronXL的授權起價為$749。