Установка цвета фона ячейки таблицы в Word [docx] [Python 3.8.2] - PullRequest
0 голосов
/ 31 марта 2020

У меня проблемы с пониманием того, как установить цвет фона ячейки таблицы.

Я перепробовал много комбинаций, но единственное, что мне удалось сделать, это установить стиль абзаца.

import docx    

doc = docx.Document()

records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
    )

table = doc.add_table(rows=1, cols=3)

hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].add_paragraph(str(qty), "Title 1")
    row_cells[0].text_frame.paragraph[0].font.size = Pt(12)
    row_cells[1].text = id
    row_cells[2].text = desc

doc.save("Testing.docx")

Я бы хотел установить для row_cells [0] красный фон, но я не могу этого сделать.

Как я могу это сделать?

1 Ответ

0 голосов
/ 01 апреля 2020

Эта опция все еще не поддерживается официальной библиотекой python -docx. Тем не менее, вы можете попробовать реализовать это самостоятельно. Свойство, которое вы ищете, называется затенение ячейки , расположенное в свойства ячейки .

Решение: Добавьте элемент затенения (w:shd) в свойства ячейки ( w:tcPr).

Написал простую функцию, которая делает именно это:

def _set_cell_background(cell, fill, color=None, val=None):
    """
    @fill: Specifies the color to be used for the background
    @color: Specifies the color to be used for any foreground
    pattern specified with the val attribute
    @val: Specifies the pattern to be used to lay the pattern
    color over the background color.
    """
    from docx.oxml.shared import qn  # feel free to move these out
    from docx.oxml.xmlchemy import OxmlElement

    cell_properties = cell._element.tcPr
    try:
        cell_shading = cell_properties.xpath('w:shd')[0]  # in case there's already shading
    except IndexError:
        cell_shading = OxmlElement('w:shd') # add new w:shd element to it
    if fill:
        cell_shading.set(qn('w:fill'), fill)  # set fill property, respecting namespace
    if color:
        pass # TODO
    if val:
        pass # TODO
    cell_properties.append(cell_shading)  # finally extend cell props with shading element

Не стесняйтесь расширять другие свойства, если вам нужны em.

Итак, основываясь на ваших Например, если у вас есть таблица, перед сохранением do c добавьте следующую строку:

.
.
_set_cell_background(table.rows[0].cells[0], 'FF0000')
doc.save("Testing.docx")

Кроме того, вы можете внести свой вклад в официальную библиотеку, зарегистрировав этот новый элемент здесь: https://github.com/python-openxml/python-docx/blob/master/docx/oxml/table.py#L753. :)

Надеюсь, это поможет,

...