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

Create, Read and Edit Excel Files in .NET MAUI

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

class="hsg-featured-snippet">

如何在 .NET MAUI 中讀取 Excel 文件

  1. 安裝 C# 庫以讀取 Excel 文件
  2. 確保所有運行 MAUI 應用程序所需的包都已安裝
  3. 在 Maui 中使用直觀的 API 創建 Excel 文件
  4. 在瀏覽器中加載和查看 Excel 文件
  5. 保存和導出 Excel 文件

安裝 IronXL

立即開始在您的項目中使用 IronXL 並免費試用。

第一步:
green arrow pointer


要安裝 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 文件。兩個元素都嵌套在一個九宮格的父元素中,因此它們在所有支持的設備上將垂直對齊。

創建 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 創建了一個工作簿和工作表,設置了單元格值並格式化了單元格。 它還演示了如何使用 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 項目。 成功執行後,將打開一個窗口,顯示下圖中的內容。

class="content-img-align-center">
class="center-image-wrapper"> Read, Create, and Edit Excel Files in .NET MAUI, Figure 1: Output

圖1 - 輸出

點擊 "創建 Excel 文件" 按鈕將打開一個單獨的對話框窗口。 此窗口提示用戶選擇一個位置和一個文件名以保存新的(生成的) Excel 文件。按照指示指定位置和文件名,然後點擊確定。 之後,另一個對話框將出現。

class="content-img-align-center">
class="center-image-wrapper"> Read, Create, and Edit Excel Files in .NET MAUI, Figure 2: Create Excel Popup

圖2 - 創建 Excel 彈出窗口

按照彈出窗口中的指示打開 Excel 文件將顯示如下截圖所示的文檔。

class="content-img-align-center">
class="center-image-wrapper"> Read, Create, and Edit Excel Files in .NET MAUI, Figure 3: Output

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

點擊 "讀取和修改 Excel 文件" 按鈕將加載以前生成的 Excel 文件並使用我們在上部分中定義的自定義背景和文本顏色修改它。

class="content-img-align-center">
class="center-image-wrapper"> Read, Create, and Edit Excel Files in .NET MAUI, Figure 4: Excel Output

圖4 - Excel 輸出

當您打開修改過的文件時,您將看到包含目錄的以下輸出。

class="content-img-align-center">
class="center-image-wrapper"> 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 套件。此外,IronXL 支持多種操作,如創建工作簿和工作表、處理單元格範圍、格式化和導出到各種文件類型如 CSV、TSV 等。

IronXL 支持所有項目模板,如 Windows Form、WPF、ASP.NET Core 等。 Refer to our tutorials for creating Excel files and reading Excel files for additional information about how to use IronXL.


class="tutorial-segment-title">快速訪問鏈接

class="tutorial-section">
class="row">
class="col-sm-8">

在 GitHub 上探索此操作指南

此項目的源代碼可在 GitHub 上獲得。

利用此代碼輕鬆在幾分鐘內啟動和運行。該項目保存為 Microsoft Visual Studio 2022 項目,但與任何 .NET IDE 兼容。

如何在 .NET MAUI 應用中讀取、創建和編輯 Excel 文件
class="col-sm-4">
class="tutorial-image"> Github Icon related to class=快速訪問鏈接" class="img-responsive add-shadow img-responsive img-popup" src="/img/svgs/github-icon.svg" loading="lazy">
class="tutorial-section">
class="row">
class="col-sm-4">
class="tutorial-image"> Documentation related to class=快速訪問鏈接" class="img-responsive add-shadow img-responsive img-popup" src="/img/svgs/documentation.svg" loading="lazy">
class="col-sm-8">

查看 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
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 1,686,155 | 版本: 2025.11 剛剛發布