How to access columns in a table that have different cell widths from MS Word
I am trying to get the cells from 1st column in a table. Getting exception in the "Foreach(Cells c in rng.Tables[1].Co开发者_如何学运维lumns[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)
{
//....
}
}
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;
}
}
}
精彩评论