问题描述
我正在使用 python-docx 创建一个所有单元格都有边框的表格。当我合并单元格涉及外部单元格时,一些外部边界消失。我使用其他 stackoverflow 问题中的函数 - 在下面的代码中显示为注释的链接 - 来设置单元格边框。如何解决这个问题,以便在合并的单元格中显示外边框?
错误的边界:
良好的边框:
工作示例:
from docx import Document
from docx.oxml.shared import OxmlElement,qn
# from https://stackoverflow.com/questions/33069697/how-to-setup-cell-borders-with-python-docx
def set_cell_edges(cell,edges,color,style,width):
"""
Parameter Type DeFinition
=========== ==================== ==========================================================================================
cell Cell Cell to apply edges
edges str,list,None Cell edges,options are 'top','bottom','start' and 'end'
color str Edge color
style str Edge style,options are 'single','dotted','dashed','dashdotted' and 'double',width int,float Edge width in points
"""
kwargs = dict()
for edge in edges:
kwargs[edge] = {'sz': width,'val': style,'color': color}
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
# check for tag existance,if none found then create one
tcBorders = tcPr.first_child_found_in("w:tcBorders")
if tcBorders is None:
tcBorders = OxmlElement('w:tcBorders')
tcPr.append(tcBorders)
# list over all available tags
for edge in ('start','top','end','insideH','insideV'):
edge_data = kwargs.get(edge)
if edge_data:
tag = 'w:{}'.format(edge)
# check for tag existance,if none found,then create one
element = tcBorders.find(qn(tag))
if element is None:
element = OxmlElement(tag)
tcBorders.append(element)
# looks like order of attributes is important
for key in ["sz","val","color","space","shadow"]:
if key in edge_data:
element.set(qn('w:{}'.format(key)),str(edge_data[key]))
if __name__ == '__main__':
rows = 3
columns = 3
document = Document()
# create table
table = document.add_table(rows=rows,cols=columns)
# merge cells
scell = table.rows[1].cells[1]
ecell = table.rows[2].cells[2]
scell.merge(ecell)
# set 4 borders in all cells
for row in table.rows:
for cell in row.cells:
set_cell_edges(cell,['top','start','end'],'#ff0000','single',1)
document.save('test.docx')
当然,我可以设置额外的列和行来设置特定的边框。但是如果没有那个技巧就可以修复它会很好。技巧示例。
带有技巧的良好边框:
if __name__ == '__main__':
rows = 3
columns = 3
document = Document()
# create table
table = document.add_table(rows=rows+1,cols=columns+1)
# merge cells
scell = table.rows[1].cells[1]
ecell = table.rows[2].cells[2]
scell.merge(ecell)
# set 4 borders in all cells
for row in table.rows[:-1]:
for cell in row.cells[:-1]:
set_cell_edges(cell,1)
# set top border in last row
for cell in table.rows[-1].cells[:-1]:
set_cell_edges(cell,['top'],1)
# set left border in last column
for cell in table.columns[-1].cells[:-1]:
set_cell_edges(cell,['start'],1)
document.save('test.docx')
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)