对于在 python 中编辑
.docx
文件,python-docx
会公开一些属性,但不会公开其他属性。可以轻松设置粗体、斜体等文本属性,但背景阴影和边框等单元格属性却无法设置。
您在python-docx
中
可以做的是使用
.xml
属性查看单元格的xml。因此 cell._tc.xml
揭示了细胞属性保存在 <w:tcPr> ... </w:tcPr>
块中。例如,这可以是嵌套结构
<w:tcPr>
<w:tcW w:w="1139" w:type="dxa"/>
<w:tcBorders>
<w:left w:val="single" w:sz="4" w:space="0" w:color="000000"/>
<w:bottom w:val="single" w:sz="4" w:space="0" w:color="000000"/>
</w:tcBorders>
<w:shd w:fill="FFDBB6" w:val="clear"/>
</w:tcPr>
我想将精确的单元格属性从一个单元格复制到另一个单元格。我试过:
<w:tcPr>
块从一个单元格复制到另一个单元格即可。但是, .xml
属性是只读的 - python-docx
不允许直接设置 xml。for child in source_cell._tc.get_or_add_tcPr().iterchildren():
dest_cell._tc.get_or_add_tcPr().insert(child)
但这正在提高
TypeError: Argument must be bytes or unicode, got 'CT_TcPr'
。
我怎样才能实现这个目标?
下面的函数似乎可以解决问题。发帖以防对其他人有帮助:
def copy_cell_properties(source_cell, dest_cell):
'''Copies cell properties from source cell to destination cell.
Copies cell background shading, borders etc.
Args:
source_cell (docx.table._Cell): the source cell with desired formatting
dest_cell (docx.table._Cell): the destination cell to which to apply formatting
'''
# get properties from source cell
# tcPr = table cell properties
cell_properties = source_cell._tc.get_or_add_tcPr()
# remove any table cell properties from destination cell
# (otherwise, we end up with two <w:tcPr> ... </w:tcPr> blocks)
dest_cell._tc.remove(dest_cell._tc.get_or_add_tcPr())
# make a shallow copy of the source cell properties
# (otherwise, properties get *moved* from source to destination)
cell_properties = copy.copy(cell_properties)
# append the copy of properties from the source cell, to the destination cell
dest_cell._tc.append(cell_properties)