在 .NET MAUI 中建立、讀取和編輯 Excel 文件
介紹
*本操作指南說明如何使用 IronXL 在 Windows 的 .NET MAUI 應用程式中建立和讀取 Excel 檔案。 我們開始吧。 *
IronXL:C# Excel 程式庫
IronXL 是一個用於讀取、寫入和操作 Excel 檔案的 C# .NET 函式庫。 它允許使用者從頭開始建立 Excel 文檔,包括 Excel 的內容和外觀,以及標題和作者等元資料。 該庫還支援使用者介面自訂功能,例如設定邊距、方向、頁面大小、圖像等。 它不需要任何外部框架、平台整合或其他第三方程式庫即可產生 Excel 檔案。 它是自包含且獨立的。
如何在 .NET 中讀取 Excel 檔案 MAUI
- 安裝C#程式庫以讀取Excel檔案
- 確保安裝了運行 MAUI 應用程式所需的所有套件
- 在 Maui 中使用直觀的 API 創建 Excel 文件
- 在瀏覽器中加載和查看 Excel 文件
- 保存和匯出 Excel 文件
安裝 IronXL
若要安裝 IronXL,您可以使用 Visual Studio 中的 NuGet 套件管理器控制台。 開啟控制台並輸入以下命令來安裝 IronXL 庫。
使用IronXL在C#中創建Excel文件
設計應用程式前端
打開名為MainPage.xaml的XAML頁面,並用以下程式碼片段替換其中的程式碼。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MAUI_IronXL.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<Label
Text="Welcome to .NET Multi-platform App UI"
SemanticProperties.HeadingLevel="Level2"
SemanticProperties.Description="Welcome Multi-platform App UI"
FontSize="18"
HorizontalOptions="Center" />
<Button
x:Name="createBtn"
Text="Create Excel File"
SemanticProperties.Hint="Click on the button to create Excel file"
Clicked="CreateExcel"
HorizontalOptions="Center" />
<Button
x:Name="readExcel"
Text="Read and Modify Excel file"
SemanticProperties.Hint="Click on the button to read Excel file"
Clicked="ReadExcel"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
上面的程式碼創建了我們基本的 .NET MAUI 應用程式的佈局。 它會創建一個標籤和兩個按鈕。 一個按鈕用於建立 Excel 文件,另一個按鈕用於讀取和修改 Excel 文件。這兩個元素都嵌套在 VerticalStackLayout 父元素中,以便在所有支援的裝置上垂直對齊顯示。
建立 Excel 文件
現在是時候使用 IronXL 建立 Excel 檔案了。 打開MainPage.xaml.cs檔案,並在檔案中撰寫以下方法。
private void CreateExcel(object sender, EventArgs e)
{
// Create a new Workbook
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a Worksheet
var sheet = workbook.CreateWorkSheet("2022 Budget");
// Set cell headers
sheet["A1"].Value = "January";
sheet["B1"].Value = "February";
sheet["C1"].Value = "March";
sheet["D1"].Value = "April";
sheet["E1"].Value = "May";
sheet["F1"].Value = "June";
sheet["G1"].Value = "July";
sheet["H1"].Value = "August";
// Fill worksheet cells with random values
Random r = new Random();
for (int i = 2; i <= 11; i++)
{
sheet["A" + i].Value = r.Next(1, 1000);
sheet["B" + i].Value = r.Next(1000, 2000);
sheet["C" + i].Value = r.Next(2000, 3000);
sheet["D" + i].Value = r.Next(3000, 4000);
sheet["E" + i].Value = r.Next(4000, 5000);
sheet["F" + i].Value = r.Next(5000, 6000);
sheet["G" + i].Value = r.Next(6000, 7000);
sheet["H" + i].Value = r.Next(7000, 8000);
}
// Apply formatting (background and border)
sheet["A1:H1"].Style.SetBackgroundColor("#d3d3d3");
sheet["A1:H1"].Style.TopBorder.SetColor("#000000");
sheet["A1:H1"].Style.BottomBorder.SetColor("#000000");
sheet["H2:H11"].Style.RightBorder.SetColor("#000000");
sheet["H2:H11"].Style.RightBorder.Type = IronXL.Styles.BorderType.Medium;
sheet["A11:H11"].Style.BottomBorder.SetColor("#000000");
sheet["A11:H11"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium;
// Apply formulas
decimal sum = sheet["A2:A11"].Sum();
decimal avg = sheet["B2:B11"].Avg();
decimal max = sheet["C2:C11"].Max();
decimal min = sheet["D2:D11"].Min();
sheet["A12"].Value = "Sum";
sheet["B12"].Value = sum;
sheet["C12"].Value = "Avg";
sheet["D12"].Value = avg;
sheet["E12"].Value = "Max";
sheet["F12"].Value = max;
sheet["G12"].Value = "Min";
sheet["H12"].Value = min;
// Save and open the Excel file
SaveService saveService = new SaveService();
saveService.SaveAndView("Budget.xlsx", "application/octet-stream", workbook.ToStream());
}Private Sub CreateExcel(ByVal sender As Object, ByVal e As EventArgs)
' Create a new Workbook
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Create a Worksheet
Dim sheet = workbook.CreateWorkSheet("2022 Budget")
' Set cell headers
sheet("A1").Value = "January"
sheet("B1").Value = "February"
sheet("C1").Value = "March"
sheet("D1").Value = "April"
sheet("E1").Value = "May"
sheet("F1").Value = "June"
sheet("G1").Value = "July"
sheet("H1").Value = "August"
' Fill worksheet cells with random values
Dim r As New Random()
For i As Integer = 2 To 11
sheet("A" & i).Value = r.Next(1, 1000)
sheet("B" & i).Value = r.Next(1000, 2000)
sheet("C" & i).Value = r.Next(2000, 3000)
sheet("D" & i).Value = r.Next(3000, 4000)
sheet("E" & i).Value = r.Next(4000, 5000)
sheet("F" & i).Value = r.Next(5000, 6000)
sheet("G" & i).Value = r.Next(6000, 7000)
sheet("H" & i).Value = r.Next(7000, 8000)
Next i
' Apply formatting (background and border)
sheet("A1:H1").Style.SetBackgroundColor("#d3d3d3")
sheet("A1:H1").Style.TopBorder.SetColor("#000000")
sheet("A1:H1").Style.BottomBorder.SetColor("#000000")
sheet("H2:H11").Style.RightBorder.SetColor("#000000")
sheet("H2:H11").Style.RightBorder.Type = IronXL.Styles.BorderType.Medium
sheet("A11:H11").Style.BottomBorder.SetColor("#000000")
sheet("A11:H11").Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium
' Apply formulas
Dim sum As Decimal = sheet("A2:A11").Sum()
Dim avg As Decimal = sheet("B2:B11").Avg()
Dim max As Decimal = sheet("C2:C11").Max()
Dim min As Decimal = sheet("D2:D11").Min()
sheet("A12").Value = "Sum"
sheet("B12").Value = sum
sheet("C12").Value = "Avg"
sheet("D12").Value = avg
sheet("E12").Value = "Max"
sheet("F12").Value = max
sheet("G12").Value = "Min"
sheet("H12").Value = min
' Save and open the Excel file
Dim saveService As New SaveService()
saveService.SaveAndView("Budget.xlsx", "application/octet-stream", workbook.ToStream())
End SubPrivate Sub CreateExcel(ByVal sender As Object, ByVal e As EventArgs)
' Create a new Workbook
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Create a Worksheet
Dim sheet = workbook.CreateWorkSheet("2022 Budget")
' Set cell headers
sheet("A1").Value = "January"
sheet("B1").Value = "February"
sheet("C1").Value = "March"
sheet("D1").Value = "April"
sheet("E1").Value = "May"
sheet("F1").Value = "June"
sheet("G1").Value = "July"
sheet("H1").Value = "August"
' Fill worksheet cells with random values
Dim r As New Random()
For i As Integer = 2 To 11
sheet("A" & i).Value = r.Next(1, 1000)
sheet("B" & i).Value = r.Next(1000, 2000)
sheet("C" & i).Value = r.Next(2000, 3000)
sheet("D" & i).Value = r.Next(3000, 4000)
sheet("E" & i).Value = r.Next(4000, 5000)
sheet("F" & i).Value = r.Next(5000, 6000)
sheet("G" & i).Value = r.Next(6000, 7000)
sheet("H" & i).Value = r.Next(7000, 8000)
Next i
' Apply formatting (background and border)
sheet("A1:H1").Style.SetBackgroundColor("#d3d3d3")
sheet("A1:H1").Style.TopBorder.SetColor("#000000")
sheet("A1:H1").Style.BottomBorder.SetColor("#000000")
sheet("H2:H11").Style.RightBorder.SetColor("#000000")
sheet("H2:H11").Style.RightBorder.Type = IronXL.Styles.BorderType.Medium
sheet("A11:H11").Style.BottomBorder.SetColor("#000000")
sheet("A11:H11").Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium
' Apply formulas
Dim sum As Decimal = sheet("A2:A11").Sum()
Dim avg As Decimal = sheet("B2:B11").Avg()
Dim max As Decimal = sheet("C2:C11").Max()
Dim min As Decimal = sheet("D2:D11").Min()
sheet("A12").Value = "Sum"
sheet("B12").Value = sum
sheet("C12").Value = "Avg"
sheet("D12").Value = avg
sheet("E12").Value = "Max"
sheet("F12").Value = max
sheet("G12").Value = "Min"
sheet("H12").Value = min
' Save and open the Excel file
Dim saveService As New SaveService()
saveService.SaveAndView("Budget.xlsx", "application/octet-stream", workbook.ToStream())
End Sub這段原始碼使用 IronXL 建立工作簿和工作表,設定儲存格值,並設定儲存格格式。 它還示範如何將 Excel 公式與 IronXL 結合使用。
在瀏覽器中查看 Excel 文件
打開MainPage.xaml.cs檔案,並撰寫以下程式碼。
private void ReadExcel(object sender, EventArgs e)
{
// Store the path of the file
string filepath = @"C:\Files\Customer Data.xlsx";
WorkBook workbook = WorkBook.Load(filepath);
WorkSheet sheet = workbook.WorkSheets.First();
// Calculate the sum of a range
decimal sum = sheet["B2:B10"].Sum();
// Modify a cell value and apply styles
sheet["B11"].Value = sum;
sheet["B11"].Style.SetBackgroundColor("#808080");
sheet["B11"].Style.Font.SetColor("#ffffff");
// Save and open the Excel file
SaveService saveService = new SaveService();
saveService.SaveAndView("Modified Data.xlsx", "application/octet-stream", workbook.ToStream());
DisplayAlert("Notification", "Excel file has been modified!", "OK");
}private void ReadExcel(object sender, EventArgs e)
{
// Store the path of the file
string filepath = @"C:\Files\Customer Data.xlsx";
WorkBook workbook = WorkBook.Load(filepath);
WorkSheet sheet = workbook.WorkSheets.First();
// Calculate the sum of a range
decimal sum = sheet["B2:B10"].Sum();
// Modify a cell value and apply styles
sheet["B11"].Value = sum;
sheet["B11"].Style.SetBackgroundColor("#808080");
sheet["B11"].Style.Font.SetColor("#ffffff");
// Save and open the Excel file
SaveService saveService = new SaveService();
saveService.SaveAndView("Modified Data.xlsx", "application/octet-stream", workbook.ToStream());
DisplayAlert("Notification", "Excel file has been modified!", "OK");
}Private Sub ReadExcel(ByVal sender As Object, ByVal e As EventArgs)
' Store the path of the file
Dim filepath As String = "C:\Files\Customer Data.xlsx"
Dim workbook As WorkBook = WorkBook.Load(filepath)
Dim sheet As WorkSheet = workbook.WorkSheets.First()
' Calculate the sum of a range
Dim sum As Decimal = sheet("B2:B10").Sum()
' Modify a cell value and apply styles
sheet("B11").Value = sum
sheet("B11").Style.SetBackgroundColor("#808080")
sheet("B11").Style.Font.SetColor("#ffffff")
' Save and open the Excel file
Dim saveService As New SaveService()
saveService.SaveAndView("Modified Data.xlsx", "application/octet-stream", workbook.ToStream())
DisplayAlert("Notification", "Excel file has been modified!", "OK")
End SubPrivate Sub ReadExcel(ByVal sender As Object, ByVal e As EventArgs)
' Store the path of the file
Dim filepath As String = "C:\Files\Customer Data.xlsx"
Dim workbook As WorkBook = WorkBook.Load(filepath)
Dim sheet As WorkSheet = workbook.WorkSheets.First()
' Calculate the sum of a range
Dim sum As Decimal = sheet("B2:B10").Sum()
' Modify a cell value and apply styles
sheet("B11").Value = sum
sheet("B11").Style.SetBackgroundColor("#808080")
sheet("B11").Style.Font.SetColor("#ffffff")
' Save and open the Excel file
Dim saveService As New SaveService()
saveService.SaveAndView("Modified Data.xlsx", "application/octet-stream", workbook.ToStream())
DisplayAlert("Notification", "Excel file has been modified!", "OK")
End Sub原始程式碼載入 Excel 文件,對一系列儲存格應用公式,並使用自訂背景和文字顏色對其進行格式化。 之後,修改後的 Excel 檔案將被儲存,並顯示通知。
儲存 Excel 文件
在本節中,我們定義SaveService類別,該類別將保存我們的Excel檔案於本地儲存中。
建立一個名為「SaveService.cs」的類,並編寫以下程式碼:
using System;
using System.IO;
namespace MAUI_IronXL
{
public partial class SaveService
{
public partial void SaveAndView(string fileName, string contentType, MemoryStream stream);
}
}using System;
using System.IO;
namespace MAUI_IronXL
{
public partial class SaveService
{
public partial void SaveAndView(string fileName, string contentType, MemoryStream stream);
}
}Imports System
Imports System.IO
Namespace MAUI_IronXL
Partial Public Class SaveService
Public Partial Private Sub SaveAndView(ByVal fileName As String, ByVal contentType As String, ByVal stream As MemoryStream)
End Sub
End Class
End NamespaceImports System
Imports System.IO
Namespace MAUI_IronXL
Partial Public Class SaveService
Public Partial Private Sub SaveAndView(ByVal fileName As String, ByVal contentType As String, ByVal stream As MemoryStream)
End Sub
End Class
End Namespace接下來,在 Platforms > Windows 資料夾內建立一個名為「SaveWindows.cs」的類,並新增以下程式碼:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
namespace MAUI_IronXL
{
public partial class SaveService
{
public async partial void SaveAndView(string fileName, string contentType, MemoryStream stream)
{
StorageFile stFile;
string extension = Path.GetExtension(fileName);
IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.DefaultFileExtension = ".xlsx";
savePicker.SuggestedFileName = fileName;
savePicker.FileTypeChoices.Add("XLSX", new List<string> { ".xlsx" });
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
stFile = await savePicker.PickSaveFileAsync();
}
else
{
StorageFolder local = ApplicationData.Current.LocalFolder;
stFile = await local.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
}
if (stFile != null)
{
using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (Stream outputStream = zipStream.AsStreamForWrite())
{
outputStream.SetLength(0);
stream.WriteTo(outputStream);
await outputStream.FlushAsync();
}
}
MessageDialog msgDialog = new("Do you want to view the document?", "File has been created successfully");
UICommand yesCmd = new("Yes");
msgDialog.Commands.Add(yesCmd);
UICommand noCmd = new("No");
msgDialog.Commands.Add(noCmd);
WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);
IUICommand cmd = await msgDialog.ShowAsync();
if (cmd.Label == yesCmd.Label)
{
await Windows.System.Launcher.LaunchFileAsync(stFile);
}
}
}
}
}using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
namespace MAUI_IronXL
{
public partial class SaveService
{
public async partial void SaveAndView(string fileName, string contentType, MemoryStream stream)
{
StorageFile stFile;
string extension = Path.GetExtension(fileName);
IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.DefaultFileExtension = ".xlsx";
savePicker.SuggestedFileName = fileName;
savePicker.FileTypeChoices.Add("XLSX", new List<string> { ".xlsx" });
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
stFile = await savePicker.PickSaveFileAsync();
}
else
{
StorageFolder local = ApplicationData.Current.LocalFolder;
stFile = await local.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
}
if (stFile != null)
{
using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (Stream outputStream = zipStream.AsStreamForWrite())
{
outputStream.SetLength(0);
stream.WriteTo(outputStream);
await outputStream.FlushAsync();
}
}
MessageDialog msgDialog = new("Do you want to view the document?", "File has been created successfully");
UICommand yesCmd = new("Yes");
msgDialog.Commands.Add(yesCmd);
UICommand noCmd = new("No");
msgDialog.Commands.Add(noCmd);
WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);
IUICommand cmd = await msgDialog.ShowAsync();
if (cmd.Label == yesCmd.Label)
{
await Windows.System.Launcher.LaunchFileAsync(stFile);
}
}
}
}
}Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Runtime.InteropServices.WindowsRuntime
Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.Storage.Streams
Imports Windows.UI.Popups
Namespace MAUI_IronXL
Partial Public Class SaveService
Public Async Sub SaveAndView(ByVal fileName As String, ByVal contentType As String, ByVal stream As MemoryStream)
Dim stFile As StorageFile
Dim extension As String = Path.GetExtension(fileName)
Dim windowHandle As IntPtr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
If Not Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons") Then
Dim savePicker As New FileSavePicker()
savePicker.DefaultFileExtension = ".xlsx"
savePicker.SuggestedFileName = fileName
savePicker.FileTypeChoices.Add("XLSX", New List(Of String) From {".xlsx"})
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle)
stFile = Await savePicker.PickSaveFileAsync()
Else
Dim local As StorageFolder = ApplicationData.Current.LocalFolder
stFile = Await local.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting)
End If
If stFile IsNot Nothing Then
Using zipStream As IRandomAccessStream = Await stFile.OpenAsync(FileAccessMode.ReadWrite)
Using outputStream As Stream = zipStream.AsStreamForWrite()
outputStream.SetLength(0)
stream.WriteTo(outputStream)
Await outputStream.FlushAsync()
End Using
End Using
Dim msgDialog As New MessageDialog("Do you want to view the document?", "File has been created successfully")
Dim yesCmd As New UICommand("Yes")
msgDialog.Commands.Add(yesCmd)
Dim noCmd As New UICommand("No")
msgDialog.Commands.Add(noCmd)
WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle)
Dim cmd As IUICommand = Await msgDialog.ShowAsync()
If cmd.Label = yesCmd.Label Then
Await Windows.System.Launcher.LaunchFileAsync(stFile)
End If
End If
End Sub
End Class
End NamespaceImports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Runtime.InteropServices.WindowsRuntime
Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.Storage.Streams
Imports Windows.UI.Popups
Namespace MAUI_IronXL
Partial Public Class SaveService
Public Async Sub SaveAndView(ByVal fileName As String, ByVal contentType As String, ByVal stream As MemoryStream)
Dim stFile As StorageFile
Dim extension As String = Path.GetExtension(fileName)
Dim windowHandle As IntPtr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
If Not Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons") Then
Dim savePicker As New FileSavePicker()
savePicker.DefaultFileExtension = ".xlsx"
savePicker.SuggestedFileName = fileName
savePicker.FileTypeChoices.Add("XLSX", New List(Of String) From {".xlsx"})
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle)
stFile = Await savePicker.PickSaveFileAsync()
Else
Dim local As StorageFolder = ApplicationData.Current.LocalFolder
stFile = Await local.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting)
End If
If stFile IsNot Nothing Then
Using zipStream As IRandomAccessStream = Await stFile.OpenAsync(FileAccessMode.ReadWrite)
Using outputStream As Stream = zipStream.AsStreamForWrite()
outputStream.SetLength(0)
stream.WriteTo(outputStream)
Await outputStream.FlushAsync()
End Using
End Using
Dim msgDialog As New MessageDialog("Do you want to view the document?", "File has been created successfully")
Dim yesCmd As New UICommand("Yes")
msgDialog.Commands.Add(yesCmd)
Dim noCmd As New UICommand("No")
msgDialog.Commands.Add(noCmd)
WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle)
Dim cmd As IUICommand = Await msgDialog.ShowAsync()
If cmd.Label = yesCmd.Label Then
Await Windows.System.Launcher.LaunchFileAsync(stFile)
End If
End If
End Sub
End Class
End Namespace輸出
建置並運行 MAUI 專案。 執行成功後,將開啟一個視窗,顯示下圖所示的內容。

圖 1 -輸出
點擊「建立 Excel 檔案」按鈕將開啟一個單獨的對話方塊視窗。 此視窗提示使用者選擇儲存新產生的 Excel 檔案的位置和檔案名稱。請按照指示指定位置和檔案名,然後按一下「確定」。 之後,會跳出另一個對話框。

圖 2 -建立 Excel 彈出視窗
依照彈出視窗中的指示開啟 Excel 文件,將顯示如下螢幕截圖所示的文件。

圖 3 -讀取和修改 Excel 彈出視窗
點擊「讀取和修改 Excel 文件」按鈕,將載入先前產生的 Excel 文件,並使用我們在前面章節中定義的自訂背景和文字顏色對其進行修改。

圖 4 - Excel 輸出
開啟修改後的檔案後,您將看到以下帶有目錄的輸出。

圖 5 -修改後的 Excel 輸出
結論
本文說明如何使用 IronXL 函式庫在 .NET MAUI 應用程式中建立、讀取和修改 Excel 檔案。 IronXL性能優異,能夠快速且準確地完成所有操作。 IronXL 是一個優秀的 Excel 操作庫,效能優於 Microsoft Interop,因為它無需在電腦上安裝 Microsoft Office 套件。此外,IronXL 支援多種操作,例如建立工作簿和工作表、處理儲存格區域、設定格式以及匯出為 CSV、TSV 等多種文件格式。
IronXL 支援所有專案模板,例如 Windows Form、WPF、ASP.NET Core 等。 請參閱我們的建立Excel檔案和讀取Excel檔案的教學,以獲得有關如何使用IronXL的更多資訊。
快速訪問鏈接
在 GitHub 上查看這份操作指南。
該專案的源代碼已上傳至 GitHub。
使用此程式碼,您可以在幾分鐘內輕鬆啟動並運行專案。此專案儲存為 Microsoft Visual Studio 2022 項目,但與任何 .NET IDE 相容。
如何在 .NET MAUI 應用程式中讀取、建立和編輯 Excel 文件常見問題
什麼是IronXL?
IronXL 是一個 C# .NET 程式庫,設計用於讀取、寫入和操作 Excel 文件。它允許使用者創建、讀取和修改 Excel 文件,而不需要外部框架或第三方軟體。
我應該如何在我的 .NET MAUI 專案中安裝 IronXL?
您可以使用 Visual Studio 的 NuGet 套件管理器控制台在 .NET MAUI 專案中安裝 IronXL。只需打開控制台並輸入命令以安裝 IronXL 程式庫。
IronXL 可以用於在 .NET MAUI 中創建 Excel 文件嗎?
是的,IronXL 支援在 .NET MAUI 中創建 Excel 文件。您可以從頭生成 Excel 文件,並使用 IronXL 的直觀 API 自訂其內容、外觀和中繼資料。
能否使用 IronXL 在 .NET MAUI 中讀取和修改 Excel 文件?
當然。IronXL 允許您加載、讀取和修改現有的 Excel 文件。您可以在 .NET MAUI 應用程式中直接應用公式、設置樣式和格式化單元格。
IronXL 是否需要安裝 Microsoft Office?
不,IronXL 不需要在電腦上安裝 Microsoft Office。它是一個獨立的程式庫,表現優異,無需依賴外部應用程式。
我可以使用 IronXL 在瀏覽器中查看 Excel 文件嗎?
IronXL 允許您保存和匯出可以在瀏覽器或標準 Excel 應用程式中打開和查看的 Excel 文件,使其能夠無縫整合到網頁工作流程中。
IronXL支援哪些檔案格式?
IronXL 支援多種文件格式,包括 XLSX,並允許使用者將其工作表匯出為其他格式,如 CSV 和 TSV。
使用 IronXL 比 Microsoft Interop 有什麼好處?
IronXL 提供了多項優勢,相較於 Microsoft Interop,包括更快的性能、不依賴於 Office 套件,並且能夠有效地處理包括工作表創建、單元格格式設置和文件匯出等多種任務。
IronXL 是否與不同的 .NET 專案模板兼容?
是的,IronXL 與各種 .NET 專案模板兼容,包括 Windows Forms、WPF 和 ASP.NET Core 等。
我可以在哪裡找到使用 IronXL 的其他資源和教程?
您可以在 [Iron Software 官方網站](https://ironsoftware.com) 及其 GitHub 儲存庫找到使用 IronXL 的其他教程和資源,其中包括範例專案和 API 參考。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。