如何访问表中具有与MS Word不同的单元格宽度的列

use*_*157 5 .net c# ms-word ms-office

我正在尝试从表的第一列中获取单元格。在“ Foreach(Cells c in rng.Tables[1].Columns[1].Cells)”中获取异常,因为该表包含具有混合单元格宽度的列。

例如:在第一行中有4个单元格,在第二行中只有2个单元格(2个单元格合并在一起)

错误消息:“ 由于表具有混合的单元格宽度,因此无法访问此集合中的各个列。

Document oDoc = open word document  
foreach (Paragraph p in oDoc.Paragraphs)  
    {  
    Range rng = p.Range;  
  /* 

  */  
  foreach (Cell c in rng.Tables[1].Columns[1].Cells)  
  {  
     //....  
  }  
 }  
Run Code Online (Sandbox Code Playgroud)

Sha*_*ark 5

可以在第二个循环中使用for循环,而不是在第二个循环中使用foreach循环:

        for (int r = 1; r <= rng.Tables[1].Row.Count; r++)
        {
            for (int c = 1; c <= rng.Tables[1].Columns.Count; c++)
            {
                try
                {
                    Cell cell = table.Cell(r, c);
                    //Do what you want here with the cell
                }
                catch (Exception e)
                {
                    if (e.Message.Contains("The requested member of the collection does not exist."))
                    {
                       //Most likely a part of a merged cell, so skip over.
                    }
                    else throw;
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)