如何在 .NET MAUI 中於 Android 裝置上讀取與寫入 WORD 文件

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

.NET MAUI(多平台應用程式使用者介面)讓開發人員能夠使用單一 C# 程式碼庫,為 Android、iOS、macOS 和 Windows 建立原生應用程式。 此方法可簡化開發流程,並在所有平台上提供原生效能。

雖然 IronWord 沒有專用的 Android 套件,但透過 .NET MAUI 可在 Android 平台上順暢運作。 這意味著您可以在 Android 裝置上輕鬆建立能讀取及寫入 WORD 文件的應用程式。

步驟 1:建立您的 .NET MAUI 應用程式專案

首先開啟 Visual Studio,並建立一個新的 .NET MAUI App 專案。 此專案類型支援從單一程式碼庫建置適用於多個平台的應用程式。

請選擇一個清晰易懂的專案名稱(例如 IronWordMauiAndroid),以保持組織性。 此架構為開發原生 Android 應用程式奠定了基礎,且僅需極少的平台專屬程式碼。

步驟 2:新增 IronWord NuGet 套件

IronWord 可透過其 NuGet 套件無縫整合至您的 .NET 專案中。 若要透過 NuGet 安裝 IronWord,請在專案上按右鍵,然後選擇"管理 NuGet 套件"。 搜尋"IronWord"並安裝最新穩定版。

此外,您亦可透過 NuGet 套件管理主控台執行以下指令,輕鬆將其加入:

Install-Package IronWord

步驟 3:在 MainPage.xaml 中設計使用者介面

為了讓使用者能在 Android 裝置上建立並儲存 WORD 文件,您將使用 XAML 設計一個簡潔明瞭的使用者介面。 此介面包含:

  • 一個多行文字編輯器,使用者可在其中輸入或編輯內容。
  • 一個"另存為 WORD 文件"按鈕,可將當前文字儲存為 .docx 檔案。
  • 狀態標籤,用於向使用者提供回饋或錯誤訊息。

以下是定義此佈局的 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="IronWordAndroid.MainPage">

    <VerticalStackLayout Padding="20" Spacing="15">
        <Editor x:Name="WordEditor"
                Placeholder="Enter your text..."
                AutoSize="TextChanges"
                HeightRequest="300"/>
        <Button Text="Save as Word Document" Clicked="OnSaveWordClicked"/>
        <Label x:Name="StatusLabel" FontSize="12" TextColor="Gray"/>
    </VerticalStackLayout>
</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="IronWordAndroid.MainPage">

    <VerticalStackLayout Padding="20" Spacing="15">
        <Editor x:Name="WordEditor"
                Placeholder="Enter your text..."
                AutoSize="TextChanges"
                HeightRequest="300"/>
        <Button Text="Save as Word Document" Clicked="OnSaveWordClicked"/>
        <Label x:Name="StatusLabel" FontSize="12" TextColor="Gray"/>
    </VerticalStackLayout>
</ContentPage>
XML

步驟 4:在 MainPage.xaml.cs 中實作文件處理功能

完成使用者介面設定後,您現在可以新增邏輯來處理文件儲存功能。 在 MainPage.xaml.cs 中,請於建構函式中設定您的 IronWord 授權金鑰,然後實作 OnSaveWordClicked 方法。

當點擊按鈕時,應用程式會建立一個新的 WordDocument,將編輯器中的文字作為段落加入,並儲存檔案。在 Android 系統上,檔案會儲存至"下載"資料夾; 在其他平台上,它會使用應用程式的快取目錄。

try-catch 區塊可確保任何錯誤皆能被擷取,並顯示於狀態標籤中。

以下是完整的運作程式碼:

using IronWord;
using IronWord.Models;
using Microsoft.Maui.Storage;
using System.Text;

namespace IronWordAndroid;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        // Set your IronWord license key
        License.LicenseKey = "YOUR-LICENSE-KEY";
    }

    private async void OnSaveWordClicked(object sender, EventArgs e)
    {
        try
        {
            // Create new Word document
            var document = new WordDocument();
            Paragraph paragraph = new Paragraph(new TextContent(WordEditor.Text));
            // Add basic text content
            document.AddParagraph(paragraph);

            // Generate a filename
            string fileName = $"MyWordDoc_{DateTime.Now:yyyyMMddHHmmss}.docx";

#if ANDROID
            string filePath = Path.Combine("/storage/emulated/0/Download", fileName);
#else
            string filePath = Path.Combine(FileSystem.CacheDirectory, fileName);
#endif

            // Save to path
            document.SaveAs(filePath);

            StatusLabel.Text = $"Saved to: {filePath}";
            await DisplayAlert("Success", $"File saved: {filePath}", "OK");
        }
        catch (Exception ex)
        {
            StatusLabel.Text = $"Error: {ex.Message}";
        }
    }
}
using IronWord;
using IronWord.Models;
using Microsoft.Maui.Storage;
using System.Text;

namespace IronWordAndroid;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        // Set your IronWord license key
        License.LicenseKey = "YOUR-LICENSE-KEY";
    }

    private async void OnSaveWordClicked(object sender, EventArgs e)
    {
        try
        {
            // Create new Word document
            var document = new WordDocument();
            Paragraph paragraph = new Paragraph(new TextContent(WordEditor.Text));
            // Add basic text content
            document.AddParagraph(paragraph);

            // Generate a filename
            string fileName = $"MyWordDoc_{DateTime.Now:yyyyMMddHHmmss}.docx";

#if ANDROID
            string filePath = Path.Combine("/storage/emulated/0/Download", fileName);
#else
            string filePath = Path.Combine(FileSystem.CacheDirectory, fileName);
#endif

            // Save to path
            document.SaveAs(filePath);

            StatusLabel.Text = $"Saved to: {filePath}";
            await DisplayAlert("Success", $"File saved: {filePath}", "OK");
        }
        catch (Exception ex)
        {
            StatusLabel.Text = $"Error: {ex.Message}";
        }
    }
}
Imports IronWord
Imports IronWord.Models
Imports Microsoft.Maui.Storage
Imports System.Text

Namespace IronWordAndroid

	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			InitializeComponent()

			' Set your IronWord license key
			License.LicenseKey = "YOUR-LICENSE-KEY"
		End Sub

		Private Async Sub OnSaveWordClicked(ByVal sender As Object, ByVal e As EventArgs)
			Try
				' Create new Word document
				Dim document = New WordDocument()
				Dim paragraph As New Paragraph(New TextContent(WordEditor.Text))
				' Add basic text content
				document.AddParagraph(paragraph)

				' Generate a filename
				Dim fileName As String = $"MyWordDoc_{DateTime.Now:yyyyMMddHHmmss}.docx"

#If ANDROID Then
				Dim filePath As String = Path.Combine("/storage/emulated/0/Download", fileName)
#Else
				Dim filePath As String = Path.Combine(FileSystem.CacheDirectory, fileName)
#End If

				' Save to path
				document.SaveAs(filePath)

				StatusLabel.Text = $"Saved to: {filePath}"
				Await DisplayAlert("Success", $"File saved: {filePath}", "OK")
			Catch ex As Exception
				StatusLabel.Text = $"Error: {ex.Message}"
			End Try
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

步驟 5:在 Android 上執行您的應用程式

直接從 Visual Studio 輕鬆將您的應用程式部署至 Android 模擬器或實體裝置。 這讓您能夠快速測試關鍵功能,例如開啟 WORD 文件、編輯內容以及儲存任何變更。

整合原生 Android 檔案選擇器,能為使用者提供流暢且熟悉的體驗,從而提升整體易用性。

由於 IronWord 完全在 .NET 環境中運行,因此無需額外的 SDK 或特定平台的依賴項,使您的應用程式更易於開發、維護和發佈。

常見問題

什麼是 IronWord?

IronWord 是由 Iron Software 開發的程式庫,讓開發者能在應用程式中處理 Word 文件,包括使用 .NET MAUI 的 Android 應用程式。

如何將 IronWord 整合到 Android 應用程式中?

您可以透過 Iron Software 網站上的設定說明,將 IronWord 整合至您的 Android 應用程式中,該說明將引導您將此程式庫加入 .NET MAUI 專案。

使用 IronWord 進行 Android 開發有哪些好處?

IronWord 提供了一種簡單且高效的方式,可在 Android 應用程式中讀取、寫入及處理 Word 文件,並利用 .NET MAUI 的強大功能實現無縫的跨平台開發。

IronWord 能否處理複雜的 WORD 文件?

是的,IronWord 專為處理複雜的 WORD 文件而設計,包括具有進階格式設定和嵌入式元素的文件,使其成為開發人員的強大選擇。

IronWord 是否與 .NET MAUI 相容?

是的,IronWord 完全相容於 .NET MAUI,讓開發人員能夠建立具備 Word 文件處理功能的跨平台應用程式。

IronWord 可以處理哪些檔案格式?

IronWord 主要支援 DOCX 和 DOC 等 WORD 文件格式,提供讀取與寫入這些檔案的全面功能。

IronWord 是否支援 Android 上的文件轉換?

IronWord 支援文件轉換功能,讓開發人員能在 Android 應用程式中,依需求將 WORD 文件轉換為其他格式。

IronWord 有提供試用版嗎?

是的,Iron Software 提供 IronWord 的免費試用版,讓開發人員在決定購買前,能先探索其各項功能與特性。

IronWord 用戶可獲得哪些支援服務?

Iron Software 為 IronWord 使用者提供全面支援,包括文件、教學指南,以及專屬的支援團隊,協助解決任何問題。

IronWord 能否用於在 Android 上建立 WORD 範本?

是的,IronWord 可用於建立及處理 WORD 範本,因此非常適合需要在 Android 裝置上進行範本化文件生成的應用程式。

Kye Stuart
技術撰稿人

Kye Stuart 在 Iron Software 將編程熱情與寫作技巧完美結合。他們曾於 Yoobee College 修習軟體部署課程,如今專注於將複雜的技術概念轉化為淺顯易懂的教育內容。Kye 重視終身學習,並樂於迎接新的技術挑戰。

工作之餘,他熱衷於 PC 遊戲、在 Twitch 進行直播,以及園藝和遛狗(愛犬名為 Jaiya)等戶外活動。Kye 直率坦誠的作風,使其成為 Iron Software 實現「為全球開發者解構技術神秘面紗」這項使命的關鍵人物。

準備開始了嗎?
Nuget 下載 44,829 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronWord
執行範例 觀看您的資料轉為 WORD 文件。