如何使用 python-docx 覆盖单元格的 xml 内容

问题描述 投票:0回答:1

对于在 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>

我想将精确的单元格属性从一个单元格复制到另一个单元格。我试过:

  1. 只需将 xml
    <w:tcPr>
    块从一个单元格复制到另一个单元格即可。但是,
    .xml
    属性是只读的 -
    python-docx
    不允许直接设置 xml。
  2. 递归循环源单元格的 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'

我怎样才能实现这个目标?

python xml docx python-docx
1个回答
0
投票

下面的函数似乎可以解决问题。发帖以防对其他人有帮助:

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)

© www.soinside.com 2019 - 2024. All rights reserved.