How to access columns in a table that have different cell widths from MS Word

本小妞迷上赌 提交于 2019-12-01 03:19:00

问题


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


来源:https://stackoverflow.com/questions/5399061/how-to-access-columns-in-a-table-that-have-different-cell-widths-from-ms-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!