IronXL 開始使用 .NET MAUI Excel 在.NET MAUI中建立、讀取和編輯 Excel 文件 Curtis Chau 更新:2026年1月20日 下載 IronXL NuGet 下載 DLL 下載 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 This article was translated from English: Does it need improvement? Translated View the article in English 介紹 本操作指南說明如何使用IronXL在 Windows 的.NET MAUI應用程式中建立和讀取 Excel 檔案。 我們開始吧。 IronXL:C# Excel 函式庫 IronXL是一個用於讀取、寫入和操作 Excel 檔案的 C# .NET函式庫。 它允許使用者從頭開始建立 Excel 文檔,包括 Excel 的內容和外觀,以及標題和作者等元資料。 該庫還支援使用者介面自訂功能,例如設定邊距、方向、頁面大小、圖像等。 它不需要任何外部框架、平台整合或其他第三方程式庫即可產生 Excel 檔案。 它是自包含且獨立的。 如何在.NET MAUI 安裝 C# 庫以讀取 Excel 文件 請確保已安裝運行 MAUI 應用程式所需的所有軟體包。 在毛伊島使用直覺的 API 建立 Excel 文件 在瀏覽器中載入並檢視 Excel 文件 儲存並匯出 Excel 文件 安裝IronXL 要安裝IronXL,您可以使用 Visual Studio 中的NuGet套件管理器控制台。 開啟控制台並輸入以下命令來安裝IronXL庫。 Install-Package IronXL.Excel 使用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> <?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> XML 上面的程式碼創建了我們基本的.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 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()); } $vbLabelText $csharpLabel 這段原始碼使用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"); } $vbLabelText $csharpLabel 原始程式碼載入 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); } } $vbLabelText $csharpLabel 接下來,在 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); } } } } } $vbLabelText $csharpLabel 輸出 建置並運行 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等。 有關如何使用IronXL 的更多信息,請參閱我們關於創建 Excel 文件和讀取 Excel 文件的教程。 快速訪問鏈接 ### 在GitHub上查看這份操作指南。 該專案的源代碼可在GitHub上找到。 使用此程式碼,您可以在幾分鐘內輕鬆啟動並運行專案。此專案儲存為 Microsoft Visual Studio 2022 項目,但與任何.NET IDE 相容。 如何在.NET MAUI應用程式中讀取、建立和編輯 Excel 文件 ### 查看 API 參考 探索IronXL的 API 參考,其中概述了 IronXL 的所有功能、命名空間、類別、方法、欄位和枚舉的詳細資訊。 查看 API 參考 常見問題解答 如何在 .NET MAUI 應用程式中創建 Excel 文件? 要在 .NET MAUI 專案中創建 Excel 文件,請使用 IronXL 庫來初始化新的工作簿和工作表。然後,您可以設置單元格值、應用 Excel 公式,並在使用自定義 SaveService 類保存文件之前自定義格式。 我可以在 .NET MAUI 應用程式中讀取現有的 Excel 文件嗎? 是的,您可以使用 IronXL 在 .NET MAUI 應用程式中加載和讀取現有 Excel 文件。該庫允許您訪問和修改單元格值、應用公式並實現自定義格式。 使用 IronXL 在 .NET MAUI 中操作 Excel 文件有什麼好處? IronXL 提供了一個自給自足的解決方案,用於在 .NET MAUI 中操作 Excel 文件,消除了對 Microsoft Office 或 Interop 的需求。它支持高效地創建、讀取和編輯 Excel 文件,並且可以匯出到各種格式,如 CSV 和 TSV。 如何在我的 .NET MAUI 專案中安裝 IronXL? 您可以在 Visual Studio 中使用 NuGet 套件管理器控制台在您的 .NET MAUI 專案中安裝 IronXL。執行命令:Install-Package IronXL.Excel 以將該庫添加到您的專案中。 在 .NET MAUI 中能夠以程式語言格式化 Excel 單元格嗎? 是的,通過 IronXL,您可以在 .NET MAUI 中以程式語言格式化 Excel 單元格。這包括設置單元格樣式、顏色和應用各種格式選項以增強 Excel 文件的外觀。 如何在我的 .NET MAUI 應用程式中實現 SaveService 類來儲存 Excel 文件? 要在 .NET MAUI 中實現 SaveService 類,您可以創建一個類,利用 IronXL 的功能來處理將 Excel 文件保存到本地存儲。這涉及定義方法以指定文件路徑和管理文件 I/O 操作。 IronXL 支持哪些 .NET 應用程式專案模板? IronXL 支持各種 .NET 專案模板,包括 Windows Forms、WPF、ASP.NET Core 等,為開發不同類型應用程式的開發人員提供了靈活性。 我在哪裡可以找到 .NET MAUI Excel 專案的原始碼? .NET MAUI 使用 IronXL 的 Excel 專案源代碼可在 GitHub 上獲得。這使開發人員能夠快速設置並在應用程式中實驗 Excel 文件操作,使用 Visual Studio 2022。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 準備好開始了嗎? Nuget 下載 1,913,565 | 版本: 2026.3 剛剛發布 開始免費試用 免費 NuGet 下載 總下載量:1,913,565 查看許可證 還在捲動嗎? 想要快速證明? PM > Install-Package IronXL.Excel 執行範例 觀看您的資料變成試算表。 免費 NuGet 下載 總下載量:1,913,565 查看許可證