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

在 .NET MAUI 中建立、讀取及編輯 Excel 檔案

This article was translated from English: Does it need improvement?
Translated
View the article in English

簡介

本操作指南說明如何在 Windows 版的 .NET MAUI 應用程式中,使用 IronXL 建立及讀取 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());
}
Private Sub CreateExcel(sender As Object, 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

    ' 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
$vbLabelText   $csharpLabel

此原始碼使用 IronXL 建立工作簿和工作表,設定儲存格值並格式化儲存格。 此外,本文亦示範如何在 IronXL 中使用 Excel 公式。

在瀏覽器中檢視 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 Sub
$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);
    }
}
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 Namespace
$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);
                }
            }
        }
    }
}
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 Namespace
$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 輸出

結論

本文說明了如何在 .NET MAUI 應用程式中,使用 IronXL程式庫來建立、讀取及修改 Excel 檔案。 IronXL 表現優異,所有操作皆能快速且精準地完成。 這是一款出色的 Excel 操作程式庫,其表現優於 Microsoft Interop,因為它無需在電腦上安裝 Microsoft Office Suite。此外,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程式庫來初始化新的工作簿和工作表。接著,您可以設定儲存格值、套用 Excel 公式並自訂格式,最後透過自訂的 SaveService 類別來儲存檔案。

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

是的,您可以在 .NET MAUI 應用程式中使用 IronXL 載入並讀取現有的 Excel 檔案。IronXL程式庫讓您能夠存取與修改儲存格值、套用公式,以及實作自訂格式。

在 .NET MAUI 中使用 IronXL 進行 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 應用程式中實作用於 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
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

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

準備開始了嗎?
Nuget 下載 2,052,917 | 版本: 2026.6 just released
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package IronXL.Excel
執行範例 觀看您的資料變成試算表。