private void ParseRows(XElement tbody, Table table, TableAnalyzer tableAnalyzer) { List <decimal> cellWidthPercentages = tableAnalyzer.CellWidthPercentages; List <decimal> tableCellWidthSums = tableAnalyzer.TableCellWidthSums; for (int r = 1; r <= table.Rows.Count; r++) { var currentRow = new XElement("tr"); tbody.Add(currentRow); decimal currentWidthSum = 0; int numColSpansUsed = 0; for (int c = 1; c <= table.Columns.Count; c++) { try { var curCell = table.Cell(r, c); curCell.Select(); var app = curCell.Application; Selection selection = app.Selection; var xmlCell = new XElement(@"td"); currentRow.Add(xmlCell); Paragraphs paragraphs = curCell.Range.Paragraphs; var tableBuilder = new TableBuilder(curCell.Tables); var paragraphsTransformer = new TableCellParagraphsTransformer(paragraphs); PopulateTableCell(xmlCell, paragraphsTransformer, tableBuilder); currentWidthSum += (decimal)curCell.Width; int widthIndex = tableCellWidthSums.IndexOf(currentWidthSum); int currentNumberOfColumns = widthIndex + 1 - numColSpansUsed; SetTableCellAttributes(xmlCell, widthIndex, currentNumberOfColumns, cellWidthPercentages, selection); numColSpansUsed += currentNumberOfColumns; } catch (System.Runtime.InteropServices.COMException) { //it seems that the only way to tell if a cell at a particular [row, col] index //exists is to call table.Cell(row, col) and see if it throws an exception //the reason it may not exist is rowspans and colspans int nr = r; while (nr > 0) { try { currentWidthSum += (decimal)table.Cell(nr, c).Width; int widthIndex = tableCellWidthSums.IndexOf(currentWidthSum); int curNumCol = widthIndex + 1 - numColSpansUsed; numColSpansUsed += curNumCol; break; } catch (System.Runtime.InteropServices.COMException) { nr--; } } } } } }
private void PopulateTableCell(XElement tableCell, TableCellParagraphsTransformer paragraphsTransformer, TableBuilder tableBuilder) { XNode currentDescendent = paragraphsTransformer.Parse(tableBuilder).FirstNode; while (currentDescendent != null) { tableCell.Add(currentDescendent); currentDescendent = currentDescendent.NextNode; } if (paragraphsTransformer.CellStyle != null) { tableCell.SetAttributeValue("class", paragraphsTransformer.CellStyle); } }