如何定义向表格单元格添加颜色的函数?

2024-04-18 21:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个程序,用彩色单元格创建docx表格。因为一个接一个地给每个单元格着色会占用很多行代码,所以我想把它放到一个函数中,但我似乎无法让它工作

这是在不使用循环的情况下为其着色的方式:

shading_elm_1 = parse_xml(r'<w:shd {} w:fill="30d1ff"/>'.format(nsdecls('w')))
            table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
            shading_elm_2 = parse_xml(r'<w:shd {} w:fill="30d1ff"/>'.format(nsdecls('w')))
            table.rows[0].cells[1]._tc.get_or_add_tcPr().append(shading_elm_2)
            shading_elm_3 = parse_xml(r'<w:shd {} w:fill="30d1ff"/>'.format(nsdecls('w')))
            table.rows[0].cells[2]._tc.get_or_add_tcPr().append(shading_elm_3)
            shading_elm_4 = parse_xml(r'<w:shd {} w:fill="30d1ff"/>'.format(nsdecls('w')))
            table.rows[0].cells[3]._tc.get_or_add_tcPr().append(shading_elm_4)
            shading_elm_5 = parse_xml(r'<w:shd {} w:fill="30d1ff"/>'.format(nsdecls('w')))
            table.rows[0].cells[4]._tc.get_or_add_tcPr().append(shading_elm_5)

这是我尝试过的功能

    def colorCells(self, table, amount, color):
        self.__amount = amount
        self.__color = "r'<w:shd {} w:fill=" + '"' + farbe + "\"/>'.format(nsdecls('w'))"
        for i in range(0, self.__amount):
            shading_elm_1 = parse_xml(self.__color)
            self.rows[0].cells[i]._tc.get_or_add_tcPr().append(shading_elm_1)

如您所见,我想将单元格的数量转换为颜色,并将颜色代码本身转换为函数 我试着这样称呼它:self.colorCells(表5,“30d1ff”)

我正在获取错误消息:

lxml.etree.XMLSyntaxError:应为开始标记“<;”未找到,第1行,第1列


Tags: orselfformatgetparsetablexmlfill