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--; } } } } } }
public XElement ParseTable(int index) { Table table = GetTable(index); _retrieved[index] = true; var root = new XElement("table"); var tbody = new XElement("tbody"); root.Add(tbody); var tableAnalyzer = new TableAnalyzer(table); //the table width value which represents a 100% width const int fullTableWidth = 514; decimal curSetWidth = Math.Truncate(tableAnalyzer.TableCellWidthSums.Last()); root.SetAttributeValue("width", (curSetWidth / fullTableWidth * 100) + "%"); root.SetAttributeValue("data-mediaid", Guid.NewGuid().ToString("N")); ParseRows(tbody, table, tableAnalyzer); return(root); }