Output table content as a string in Github-markdown format. If "clean" then markdown syntax is removed from cell content. If "fill_empty" then cell content None is replaced by the values above (columns) or left (rows) in an effort to approximate row and columns spans
(self, clean=False, fill_empty=True)
| 1595 | return table_arr |
| 1596 | |
| 1597 | def to_markdown(self, clean=False, fill_empty=True): |
| 1598 | """Output table content as a string in Github-markdown format. |
| 1599 | |
| 1600 | If "clean" then markdown syntax is removed from cell content. |
| 1601 | If "fill_empty" then cell content None is replaced by the values |
| 1602 | above (columns) or left (rows) in an effort to approximate row and |
| 1603 | columns spans. |
| 1604 | |
| 1605 | """ |
| 1606 | output = "|" |
| 1607 | rows = self.row_count |
| 1608 | cols = self.col_count |
| 1609 | |
| 1610 | # cell coordinates |
| 1611 | cell_boxes = [[c for c in r.cells] for r in self.rows] |
| 1612 | |
| 1613 | # cell text strings |
| 1614 | cells = [[None for i in range(cols)] for j in range(rows)] |
| 1615 | for i, row in enumerate(cell_boxes): |
| 1616 | for j, cell in enumerate(row): |
| 1617 | if cell is not None: |
| 1618 | cells[i][j] = extract_cells( |
| 1619 | self.textpage, cell_boxes[i][j], markdown=True |
| 1620 | ) |
| 1621 | |
| 1622 | if fill_empty: # fill "None" cells where possible |
| 1623 | |
| 1624 | # for rows, copy content from left to right |
| 1625 | for j in range(rows): |
| 1626 | for i in range(cols - 1): |
| 1627 | if cells[j][i + 1] is None: |
| 1628 | cells[j][i + 1] = cells[j][i] |
| 1629 | |
| 1630 | # for columns, copy top to bottom |
| 1631 | for i in range(cols): |
| 1632 | for j in range(rows - 1): |
| 1633 | if cells[j + 1][i] is None: |
| 1634 | cells[j + 1][i] = cells[j][i] |
| 1635 | |
| 1636 | # generate header string and MD separator |
| 1637 | for i, name in enumerate(self.header.names): |
| 1638 | if not name: # generate a name if empty |
| 1639 | name = f"Col{i+1}" |
| 1640 | name = name.replace("\n", "<br>") # use HTML line breaks |
| 1641 | if clean: # remove sensitive syntax |
| 1642 | name = html.escape(name.replace("-", "-")) |
| 1643 | output += name + "|" |
| 1644 | |
| 1645 | output += "\n" |
| 1646 | # insert GitHub header line separator |
| 1647 | output += "|" + "|".join("---" for i in range(self.col_count)) + "|\n" |
| 1648 | |
| 1649 | # skip first row in details if header is part of the table |
| 1650 | j = 0 if self.header.external else 1 |
| 1651 | |
| 1652 | # iterate over detail rows |
| 1653 | for row in cells[j:]: |
| 1654 | line = "|" |