[英]Python pptx merging table rows
我在 powerpoint 中有一個表格,其中(在使用其他函數渲染之后)每隔一行都完全為空。 我嘗試通過將每個空行與其下方的行合並來解決該問題,如下所示:
def is_empty_row(row):
for cell in row.cells:
if len(cell.text):
return False
return True
def merge_empty_row(table,index): # Assumes no 2 consecutive rows are empty!
row = table.rows[index]
try:
next_row = table.rows[index+1]
except:
return
cell_1 = row.cells[0]
cell_2 = next_row.cells[len(next_row.cells)-1]
cell_1.merge(cell_2)
def fix_tables(document):
ppt = Presentation(document)
for slide in ppt.slides:
for shape in slide.shapes:
if shape.shape_type == MSO_SHAPE_TYPE.TABLE:
for index in range(len(shape.table.rows)):
if is_empty_row(shape.table.rows[index]):
merge_empty_row(shape.table, index)
docname = "".join(document.split(".")[0])
ppt.save(docname+'.out.pptx')
我在模板 pptx 文件上從 Django 調用這個 function ,只是得到以下錯誤:
Exception Type: XMLSyntaxError at /amas/analysis/1178/report/download/34
Exception Value: Opening and ending tag mismatch: r line 2 and t, line 2, column 11532 (<string>, line 2)
有任何想法嗎?
我的第一選擇是避免插入空行。 但是,如果由於某種原因無法做到這一點,您可以嘗試像這樣刪除空行:
def delete_row(row):
tr = row._tr
tr.getparent().remove(tr)
rows = [table.rows[i] for i in range(len(rows))]
empty_rows = [r for r in rows if row_is_empty(r)]
for row in empty_rows:
delete_row(row)
您需要事先單獨識別空行,否則在迭代中間刪除它們可能會搞砸引用(更改行rows[i]
指向的行)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.