How to access columns in a table that have differe

2019-05-05 02:13发布

问题:

I am trying to get the cells from 1st column in a table. Getting exception in the "Foreach(Cells c in rng.Tables[1].Columns[1].Cells)" because the table contains columns that have mixed cell widths.

for eg: in first row, there are 4 cells and in second row, there are only 2 cells (2 cells merged together)

Error Message: "Cannot access individual columns in this collection because the table has mixed cell widths."

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)  
  {  
     //....  
  }  
 }  

回答1:

Instead of using a foreach loop in your second loop, can you instead use a for loop like so to iterate over all cells:

        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;
                }
            }
        }