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

Aru*_*ngh 1 .net c# ms-word office-interop

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

到目前为止,一切都运行良好。

现在我有一些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.
Run Code Online (Sandbox Code Playgroud)

问题: 1. 读取表时,使用时只读取第一列 wordApp.Selection.endKey

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

在此处输入图片说明

小智 8

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

        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);
        }
Run Code Online (Sandbox Code Playgroud)