You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP(C#)读取Word文档文本求助,求可用代码示例

当然有办法搞定!我之前在UWP项目里刚好做过类似的需求,给你分享两种经过验证的可行方案,你可以根据自己的场景选择:

方案1:使用Open XML SDK(推荐,无需依赖Office环境)

这是最通用的方案,不需要用户安装Office,纯代码就能处理.docx格式的Word文档,步骤如下:

  1. 首先在你的UWP项目中安装NuGet包:DocumentFormat.OpenXml和DocumentFormat.OpenXml.Packaging
  2. 编写读取文本的方法,利用StorageFile的流来解析文档:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Text;
using Windows.Storage;
using System.IO;

public async Task<string> ExtractTextFromWordFile(StorageFile targetFile)
{
    // 先校验文件有效性
    if (targetFile == null || !targetFile.FileType.Equals(".docx", StringComparison.OrdinalIgnoreCase))
    {
        throw new ArgumentException("请传入有效的.docx格式文件");
    }

    var textBuilder = new StringBuilder();

    // 打开文件流并解析Word文档
    using (var stream = await targetFile.OpenAsync(FileAccessMode.Read))
    using (var wordDoc = WordprocessingDocument.Open(stream.AsStream(), isEditable: false))
    {
        var mainDocumentPart = wordDoc.MainDocumentPart;
        if (mainDocumentPart == null) return string.Empty;

        // 遍历文档中所有文本节点,拼接内容
        foreach (var textNode in mainDocumentPart.Document.Body.Descendants<Text>())
        {
            textBuilder.Append(textNode.Text);
        }
    }

    return textBuilder.ToString();
}

注意事项:

  • 这个方案只支持.docx格式,如果需要处理旧版.doc文件,建议先引导用户转成.docx,或者使用第三方收费库(比如Aspose.Words)来兼容
  • 要确保你的UWP应用拥有文件访问权限:可以在Package.appxmanifest中添加文件类型关联(指定.docx),或者声明broadFileSystemAccess权限(适用于访问任意位置文件的场景)
方案2:依赖Office Interop(仅当用户必装Office时可选)

如果你的应用目标用户肯定安装了Microsoft Office,可以用Office Interop来读取,但UWP中使用Interop需要注意权限限制,且部署起来更麻烦,代码示例如下:

using Microsoft.Office.Interop.Word;
using Windows.Storage;
using System.Threading.Tasks;

public async Task<string> ReadWordTextWithInterop(StorageFile wordFile)
{
    var app = new Application();
    Document doc = null;
    string text = string.Empty;

    try
    {
        // 获取文件本地路径(注意UWP中需要文件在可访问的位置)
        var fileLocalPath = wordFile.Path;
        doc = app.Documents.Open(fileLocalPath);
        text = doc.Content.Text;
    }
    finally
    {
        doc?.Close();
        app.Quit();
    }

    return text;
}

注意事项:

  • 必须在项目中添加Microsoft.Office.Interop.Word的引用
  • UWP应用需要在桌面桥(Desktop Bridge)下运行才能正常使用Interop,否则会有权限问题
  • 用户必须安装对应版本的Office,兼容性较差,所以一般不推荐这种方案

内容的提问来源于stack exchange,提问作者Dave Middleton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:33:36