C#将Word文档中的所有文本内容转换为大写

在C#中,要将Word文档中的所有文本内容转换为大写,可以使用 ​Microsoft.Office.Interop.Word​ 库(适用于Windows环境,需要安装Microsoft Word)或者使用更现代化的 ​Open XML SDK​(无需安装Word,但处理复杂格式较麻烦)。

图片[1]_C#将Word文档中的所有文本内容转换为大写_知途无界

这里提供 ​两种方法​:


方法1:使用 Microsoft.Office.Interop.Word(推荐,简单易用)​

适用场景​:Windows环境,已安装Microsoft Word(Office 2010或更高版本)。

步骤1:安装 NuGet 包

在 ​Visual Studio​ 中,通过 ​NuGet 包管理器​ 安装:

Install-Package Microsoft.Office.Interop.Word

或者手动安装:

Install-Package Microsoft.Office.Interop.Word -Version 15.0.4797.1004

步骤2:C# 代码实现

using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main(string[] args)
    {
        string wordFilePath = @"C:\YourFolder\YourDocument.docx"; // 替换为你的Word文件路径
        string outputPath = @"C:\YourFolder\YourDocument_Uppercase.docx"; // 输出文件路径

        // 启动Word应用程序
        Application wordApp = new Application();
        Document doc = null;

        try
        {
            // 打开Word文档
            doc = wordApp.Documents.Open(wordFilePath);

            // 遍历所有段落,将文本转换为大写
            foreach (Paragraph para in doc.Paragraphs)
            {
                para.Range.Text = para.Range.Text.ToUpper();
            }

            // 遍历所有表格单元格,将文本转换为大写
            foreach (Table table in doc.Tables)
            {
                foreach (Row row in table.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        cell.Range.Text = cell.Range.Text.ToUpper();
                    }
                }
            }

            // 保存修改后的文档
            doc.SaveAs2(outputPath);
            Console.WriteLine("Word文档已成功转换为大写,并保存到: " + outputPath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("发生错误: " + ex.Message);
        }
        finally
        {
            // 关闭文档和Word应用程序
            if (doc != null)
            {
                doc.Close(false); // 不保存原始文档
                System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
            }
            if (wordApp != null)
            {
                wordApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
            }
        }
    }
}

代码说明

  1. ​**Application wordApp = new Application();**​
    • 启动 ​Microsoft Word 应用程序​(后台运行)。
  2. ​**doc = wordApp.Documents.Open(wordFilePath);**​
    • 打开指定的 ​Word 文档​(.docx.doc)。
  3. 遍历段落 & 表格
    • ​**doc.Paragraphs**​:遍历所有段落,将文本转换为大写(ToUpper())。
    • ​**doc.Tables**​:遍历所有表格,将单元格文本转换为大写。
  4. ​**doc.SaveAs2(outputPath);**​
    • 保存修改后的文档(建议另存为新文件,避免覆盖原文件)。
  5. ​**finally 块**​
    • 释放 COM 对象​(避免内存泄漏)。
    • 关闭 Word 应用程序

方法2:使用 Open XML SDK(无需安装Word,但较复杂)​

适用场景​:​无需安装Microsoft Word,适用于 ​**.NET Core / .NET 5+​**,但 ​不处理复杂格式(如样式、表格)​

步骤1:安装 NuGet 包

Install-Package DocumentFormat.OpenXml

步骤2:C# 代码实现

using System;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

class Program
{
    static void Main(string[] args)
    {
        string wordFilePath = @"C:\YourFolder\YourDocument.docx"; // 输入文件
        string outputPath = @"C:\YourFolder\YourDocument_Uppercase.docx"; // 输出文件

        try
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(wordFilePath, true))
            {
                // 获取所有段落
                var body = doc.MainDocumentPart.Document.Body;
                foreach (var paragraph in body.Elements<Paragraph>())
                {
                    foreach (var run in paragraph.Elements<Run>())
                    {
                        foreach (var text in run.Elements<Text>())
                        {
                            text.Text = text.Text.ToUpper();
                        }
                    }
                }

                // 保存修改后的文档
                doc.SaveAs(outputPath);
                Console.WriteLine("Word文档已成功转换为大写,并保存到: " + outputPath);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("发生错误: " + ex.Message);
        }
    }
}

代码说明

  1. ​**WordprocessingDocument.Open()**​
    • 直接读取 ​**.docx 文件(XML 格式)​**,无需安装 Word。
  2. 遍历段落 & 文本
    • ​**body.Elements<Paragraph>()**​:遍历所有段落。
    • ​**paragraph.Elements<Run>()​:遍历段落中的 ​Run(文本块)​**。
    • ​**run.Elements<Text>()​:遍历 ​Run 中的文本**,并转换为大写(ToUpper())。
  3. ​**doc.SaveAs()**​
    • 保存修改后的文档。

⚠ ​缺点​:

  • 不处理表格、图片、样式​(仅修改纯文本)。
  • 不适用于 .doc(旧版 Word 格式)​

总结

方法适用场景是否需要 Word处理表格/样式推荐度
Microsoft.Office.Interop.WordWindows + 已安装 Word✅ 需要✅ 支持⭐⭐⭐⭐⭐
Open XML SDK无 Word 环境(.NET Core)❌ 不需要❌ 仅文本⭐⭐⭐

推荐选择

  • 如果你的电脑安装了 Microsoft Word​ → ​使用 Microsoft.Office.Interop.Word(方法1)​,简单可靠,支持所有格式(表格、样式等)。
  • 如果不想安装 Word(如服务器环境)​​ → ​使用 Open XML SDK(方法2)​,但仅适用于纯文本,不处理复杂格式。

你可以根据自己的需求选择合适的方法! 🚀

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞48 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容