如何使用 C# 在 .NET MAUI 中讀取和建立 Excel 檔案 | IronXL

在 .NET MAUI 中建立、讀取和編輯 Excel 文件

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 檔案。 它是自包含且獨立的。

安裝 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 專案。 執行成功後,將開啟一個窗口,顯示下圖所示的內容。

Read, Create, and Edit Excel Files in .NET MAUI, Figure 1: Output

圖 1 -輸出

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

Read, Create, and Edit Excel Files in .NET MAUI, Figure 2: Create Excel Popup

圖 2 -建立 Excel 彈出窗口

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

Read, Create, and Edit Excel Files in .NET MAUI, Figure 3: Output

圖 3 -讀取和修改 Excel 彈出窗口

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

Read, Create, and Edit Excel Files in .NET MAUI, Figure 4: Excel Output

圖 4 - Excel 輸出

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

Read, Create, and Edit Excel Files in .NET MAUI, Figure 5: Modified Excel Output

圖 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 文件
Github Icon related to 快速訪問鏈接
Documentation related to 快速訪問鏈接

查看 API 參考

探索 IronXL 的 API 參考,其中概述了 IronXL 的所有功能、命名空間、類別、方法、欄位和枚舉的詳細資訊。

查看 API 參考

常見問題解答

如何在.NET MAUI應用程式中建立Excel檔案?

若要在 .NET MAUI 專案中建立 Excel 文件,請使用 IronXL 庫初始化新的工作簿和工作表。然後,您可以使用自訂的 SaveService 類別設定儲存格值、套用 Excel 公式並自訂格式,最後儲存檔案。

我可以在 .NET MAUI 應用程式中讀取現有的 Excel 檔案嗎?

是的,您可以使用 IronXL 在 .NET MAUI 應用程式中載入和讀取現有的 Excel 檔案。該庫允許您存取和修改單元格值、應用公式以及實現自訂格式。

在 .NET MAUI 中使用 IronXL 進行 Excel 檔案操作有哪些好處?

IronXL 提供了一個基於 .NET MAUI 的獨立 Excel 檔案操作解決方案,無需 Microsoft Office 或 Interop。它支援有效率地建立、讀取和編輯 Excel 文件,並可匯出為 CSV 和 TSV 等多種格式。

如何在我的 .NET MAUI 專案中安裝 IronXL?

您可以使用 Visual Studio 中的 NuGet 套件管理器控制台將 IronXL 安裝到您的 .NET MAUI 專案中。執行命令: Install-Package IronXL.Excel將該程式庫新增至您的專案。

是否可以使用 .NET MAUI 以程式設計方式格式化 Excel 儲存格?

是的,使用 IronXL,您可以在 .NET MAUI 中以程式設計方式格式化 Excel 儲存格。這包括設定儲存格樣式、顏色以及套用各種格式選項來增強 Excel 檔案的外觀。

如何在我的 .NET MAUI 應用程式中實作用於保存 Excel 檔案的 SaveService 類別?

若要在 .NET MAUI 中實作 SaveService 類,您可以建立一個利用 IronXL 的功能將 Excel 檔案儲存到本機儲存的類別。這包括定義用於指定檔案路徑和管理檔案 I/O 操作的方法。

IronXL 在 .NET 應用程式中支援哪些專案範本?

IronXL 支援各種 .NET 專案模板,包括 Windows Forms、WPF、ASP.NET Core 等,為開發不同類型應用程式的開發人員提供了靈活性。

哪裡可以找到 .NET MAUI Excel 專案的原始碼?

使用 IronXL 的 .NET MAUI Excel 專案的原始程式碼已發佈在 GitHub 上。這使得開發人員能夠使用 Visual Studio 2022 快速設定並嘗試在應用程式中操作 Excel 檔案。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。

準備好開始了嗎?
Nuget 下載 1,802,965 | 版本: 2025.12 剛剛發布