(二)表格篇(table)(本篇)html
(三)樣式篇(style)python
選你所需便可。下面開始正文。算法
docx.tables
cell.text
for t in docx.tables: # todo
_table_list = [] for i, row in enumerate(table.rows): # 讀每行 row_content = [] for cell in row.cells: # 讀一行中的全部單元格 c = cell.text if c not in row_content: row_content.append(c) # print(row_content) _table_list.append(row_content)
['咱們來插入一個表格'] ['這是一級標題1', '這是二級標題1.1', '這是三級標題1.1.1', '總結'] ['這是一級標題1', '這是二級標題1.1', '這是三級標題1.1.2', '總結'] ['這是一級標題1', '這是二級標題1.1', '這是三級標題1.1.3', '總結'] ['這是一級標題1', '這是二級標題1.2', '這是三級標題1.2.1', '總結'] ['這是一級標題1', '這是二級標題1.3', '這是三級標題1.3.1', '總結'] ['這是一級標題1', '這是二級標題1.3', '這是三級標題1.3.2', '總結'] ['別忙,還有內容'] ['內容', '另外一段內容']
def _fill_blank(table): cols = max([len(i) for i in table]) new_table = [] for i, row in enumerate(table): new_row = [] [new_row.extend([i] * int(cols / len(row))) for i in row] print(new_row) new_table.append(new_row) return new_table
['咱們來插入一個表格', '咱們來插入一個表格', '咱們來插入一個表格', '咱們來插入一個表格'] ['這是一級標題1', '這是二級標題1.1', '這是三級標題1.1.1', '總結'] ['這是一級標題1', '這是二級標題1.1', '這是三級標題1.1.2', '總結'] ['這是一級標題1', '這是二級標題1.1', '這是三級標題1.1.3', '總結'] ['這是一級標題1', '這是二級標題1.2', '這是三級標題1.2.1', '總結'] ['這是一級標題1', '這是二級標題1.3', '這是三級標題1.3.1', '總結'] ['這是一級標題1', '這是二級標題1.3', '這是三級標題1.3.2', '總結'] ['別忙,還有內容', '別忙,還有內容', '別忙,還有內容', '別忙,還有內容'] ['內容', '內容', '另外一段內容', '另外一段內容']
<table border="1" align="center"> <tr align="center"><td colspan="4">Row One</td></tr> <tr align="center"><td>Row Two</td><td>Row Two</td><td>Row Two</td><td>Row Two</td></tr> </table>
<table border="1" align="center"> <tr><td rowspan="3">Left</td><td>Right</td></tr> <tr><td>Right</td></tr> <tr><td>Right</td></tr> </table>
def _table_matrix(): if not table: return "" # 處理同一行的各列 temp_matrix = [] for row in table: if not row: continue col_last = [row[0], 1, 1] line = [col_last] for i, j in enumerate(row): if i == 0: continue if j == col_last[0]: col_last[2] += 1 line.append(["", 0, 0]) else: col_last = [j, 1, 1] line.append(col_last) temp_matrix.append(line) # 處理不一樣行 matrix = [temp_matrix[0]] last_row = [] for i, row in enumerate(temp_matrix): if i == 0: last_row.extend(row) continue new_row = [] for p, r in enumerate(row): if p >= len(last_row): break last_pos = last_row[p] if r[0] == last_pos[0] and last_pos[0] != "": last_row[p][1] += 1 new_row.append(["", 0, 0]) else: last_row[p] = row[p] new_row.append(r) matrix.append(new_row) return matrix
def table2html(t): table = _fill_blank(t) matrix = _table_matrix(table) html = "" for row in matrix: tr = "<tr>" for col in row: if col[1] == 0 and col[2] == 0: continue td = ["<td"] if col[1] > 1: td.append(" rowspan=\"%s\"" % col[1]) if col[2] > 1: td.append(" colspan=\"%s\"" % col[2]) td.append(">%s</td>" % col[0]) tr += "".join(td) tr += "</tr>" html += tr return html
{{ table|safe }}