如何使用 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());
}
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 Sub
$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");
}
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 輸出

結論

本文說明如何使用 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 庫來初始化新的工作簿和工作表。然後,您可以設置單元格值、應用 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 bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 1,846,091 | 版本: 2026.2 剛剛發布