c# - 如何逐行阅读 MS Word 段落和表格内容

标签 c# .net ms-word office-interop

我正在使用 Microsoft.Office.Interop.Word 在 C# (3.5) 中阅读 word 文档。逐行读取,将行拆分为数组[]并处理行中的每个单词,并根据一些业务逻辑替换一些单词,并在替换单词后,将整行替换为转换后的行。

到目前为止一切正常。

现在我有一些word文档,有段落和表格。我想一一读取表格的每一列,并替换特定列中的列内容。

更新


使用办公自动化

1. Opening word file.
2. Moving cursor to top of the document
3. Selecting first line using (`wordApp.Selection.endKey`) and processing all words
4. After processing the words replacing the selected line with the processed line.
5. Using wordApp.Selection.MoveDown(ref lineCount, ref countPage, ref MISSING);    
   moving next line processed further.

问题: 1. 使用 wordApp.Selection.endKey

读取表格时,它只读取第一列

我想处理所有列的数据。 有什么方法可以识别内容是段落还是表格?

enter image description here

最佳答案

使用选择来扫描文档在性能上应该是相当昂贵的。 我建议使用以下代码:

        List<Word.Range> TablesRanges = new List<Word.Range>();

        wordApp = new Microsoft.Office.Interop.Word.Application();
        doc = wordApp.Documents.OpenNoRepairDialog(FileName: @"c:\AAAAA.docx", ConfirmConversions: false, ReadOnly: true, AddToRecentFiles: false, NoEncodingDialog: true);


        for (int iCounter = 1; iCounter <= doc.Tables.Count; iCounter++)
        {
            Word.Range TRange = doc.Tables[iCounter].Range;
            TablesRanges.Add(TRange);
        }

        Boolean bInTable;
        for (int par = 1; par <= doc.Paragraphs.Count; par++)
        {
            bInTable = false;
            Word.Range r = doc.Paragraphs[par].Range;
            foreach (Word.Range range in TablesRanges)
            {
                if (r.Start >= range.Start && r.Start <= range.End)
                {
                    Console.WriteLine("In Table - Paragraph number " + par.ToString() + ":" + r.Text);
                    bInTable = true;
                    break;
                }

            }

            if (!bInTable)
                Console.WriteLine("!!!!!! Not In Table - Paragraph number " + par.ToString() + ":" + r.Text);
        }

关于c# - 如何逐行阅读 MS Word 段落和表格内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11011759/

相关文章:

c# - 在应用程序退出时处理 RX 线程

c# - MS Word 2010 无法打开宏存储

vba - 通过 VBA excel 程序在 MS Word 标题中的边框线后添加页码和新行

c# - 我不认为我正在修改这个集合

c# - 根据 C# 中的体系结构引用不同的库

c# - 快捷方式改变相对路径?

.net - 决定 .NET Framework 版本涉及哪些因素?

C# - 使字符串以不同的方式打印到控制台,但以其原始形式在其他地方使用

c# - 过滤 XML 文档部分的有效方法

java - 是否可以使用 Apache POI 解析 MS Word 并将其转换为 XML?