python docx设置表格单元格背景和文本颜色 [英] python docx set table cell background and text color
问题描述
我在docx中使用python 2.7,我想根据条件更改表格中单元格的背景和文本颜色。
I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
我找不到任何有关单个单元格格式的有用资源
I could not find any usefull resources about single cell formatting
有任何建议吗?
编辑1
我的代码
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
所有单元格仍然相同。
推荐答案
如果要对特定单元格进行颜色填充,请在能够使用下面的代码。
例如,假设您需要使用RGB颜色1F5C8B填充表格第一行中的第一个单元格:
If you want to color fill a specific cell in a table you can use the code below. For example let's say you need to fill the first cell in the first row of your table with the RGB color 1F5C8B:
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
现在,如果您还想用相同的颜色填充第一行的第二个单元格,则应该创建一个新元素
,否则使用与上面相同的元素,填充将继续并从第一个单元格中消失...
Now if you want to also fill the second cell in the first row with the same color, you should create a new element otherwise if you use the same element as above the fill will move on and will disappear from the first cell...
shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[1]._tc.get_or_add_tcPr().append(shading_elm_2)
...以此类推,其他单元格则如此。
...and so on for other cells.
来源: https://groups.google.com/forum/#!topic/python-docx/-c3OrRHA3qo
这篇关于python docx设置表格单元格背景和文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!