python-docx设置表格填充底色以及切分单元格(仅使用python-docx)

本篇文件要解决什么

python-docx我们常用于处理word,至于建立表格什么的,自行找别的教程.本篇仅仅解决两个问题

  1. 某个单元格填充颜色的问题
  2. 切分单元格的操作,以及如何消除,切分单元格的时候,多出来的边框问题

两个网址:解决表格边框问题参考的,两个网址

#https://stackoverflow.com/questions/33069697/how-to-setup-cell-borders-with-python-docx
#http://officeopenxml.com/WPtableBorders.php

代码

1.单元格填充颜色代码:

def setCellBackgroundColor(self,cell,rgbColor):
        if not isinstance(rgbColor,RGBValue):
            print('rgbColor is not RGBValue...',type(rgbColor))
            return
        hr = str(hex(int(rgbColor.r)))[-2:]
        hg = str(hex(int(rgbColor.g)))[-2:]
        hb = str(hex(int(rgbColor.b)))[-2:]
        colorStr = hr+hg+hb
        #print(colorStr)
        shading_elm_1 = parse_xml(r''.format(nsdecls('w'),color_value = colorStr))
        cell._tc.get_or_add_tcPr().append(shading_elm_1)

2.切分单元格,以及解决残留边框问题的代码:

#简单切分单元格
def seperateCell(self,table,leftAligent=WD_ALIGN_VERTICAL.CENTER,rightAligent=WD_ALIGN_VERTICAL.CENTER,leftWidth=None):
        table.add_row()
        cell = table.rows[-1].cells[-1]
        cell.text = ""
        cell._element.clear_content()
        itb = cell.add_table(rows=1,cols=2)
        itb.style = u'Table Grid'
        leftCell = itb.rows[-1].cells[0]
        rightCell = itb.rows[-1].cells[1]
            #调整宽度,对齐方式
        allWidth = leftCell.width + rightCell.width
        
        if isinstance(leftWidth , Cm):
            leftCell.width = leftWidth
        else:
            leftCell.width = allWidth / 2
        rightCell.width = allWidth - leftCell.width
        leftCell.vertical_alignment = leftAligent
        rightCell.vertical_alignment = rightAligent
        #选择显示切分出来的单元格的哪些边框,显然leftCell只是显示右边的边界,rightCell反之
        self.justShowCellBorder(leftCell,'end')
        self.justShowCellBorder(rightCell,'start')
        return (leftCell,rightCell,itb)
  
  def set_cell_border(self,cell, **kwargs):
        tc = cell._tc
        tcPr = tc.get_or_add_tcPr()

        # check for tag existnace, if none found, then create one
        tcBorders = tcPr.first_child_found_in("w:tcBorders")
        if tcBorders is None:
            tcBorders = OxmlElement('w:tcBorders')
            tcPr.append(tcBorders)

        # list over all available tags
        for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
            edge_data = kwargs.get(edge)
            if edge_data:
                tag = 'w:{}'.format(edge)

                # check for tag existnace, if none found, then create one
                element = tcBorders.find(qn(tag))
                if element is None:
                    element = OxmlElement(tag)
                    tcBorders.append(element)

                # looks like order of attributes is important
                for key in ["sz", "val", "color", "space", "shadow"]:
                    if key in edge_data:
                        element.set(qn('w:{}'.format(key)), str(edge_data[key]))
    
    #usage:hideDirection must in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV') 
    def hideCellBorder(self,cell,hideDirection):
        if not isinstance(hideDirection , str) or not hideDirection in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
            return 
        if hideDirection == 'start':
            self.set_cell_border(cell,start={"val":"nil"})
        elif hideDirection == 'end':
            self.set_cell_border(cell,end={"val":"nil"})
        elif hideDirection == 'top':
            self.set_cell_border(cell,top={"val":"nil"})
        elif hideDirection == 'bottom':
            self.set_cell_border(cell,bottom={"val":"nil"})
        elif hideDirection == 'insideH':
            self.set_cell_border(cell,insideH={"val":"nil"})
        elif hideDirection == 'insizeV':
            self.set_cell_border(cell,insizeV={"val":"nil"})
    
    def justShowCellBorder(self,cell,direction):
        if not isinstance(direction , str) or not direction in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
            return 
        if direction == 'start':
            #self.set_cell_border(cell,start={"val":"nil"})
            self.set_cell_border(cell,end={"val":"nil"})
            self.set_cell_border(cell,top={"val":"nil"})
            self.set_cell_border(cell,bottom={"val":"nil"})
            self.set_cell_border(cell,insideH={"val":"nil"})
            self.set_cell_border(cell,insizeV={"val":"nil"})
        elif direction == 'end':
            self.set_cell_border(cell,start={"val":"nil"})
            #self.set_cell_border(cell,end={"val":"nil"})
            self.set_cell_border(cell,top={"val":"nil"})
            self.set_cell_border(cell,bottom={"val":"nil"})
            self.set_cell_border(cell,insideH={"val":"nil"})
            self.set_cell_border(cell,insizeV={"val":"nil"})
        elif direction == 'top':
            self.set_cell_border(cell,start={"val":"nil"})
            self.set_cell_border(cell,end={"val":"nil"})
            #self.set_cell_border(cell,top={"val":"nil"})
            self.set_cell_border(cell,bottom={"val":"nil"})
            self.set_cell_border(cell,insideH={"val":"nil"})
            self.set_cell_border(cell,insizeV={"val":"nil"})
        elif direction == 'bottom':
            self.set_cell_border(cell,start={"val":"nil"})
            self.set_cell_border(cell,end={"val":"nil"})
            self.set_cell_border(cell,top={"val":"nil"})
            #self.set_cell_border(cell,bottom={"val":"nil"})
            self.set_cell_border(cell,insideH={"val":"nil"})
            self.set_cell_border(cell,insizeV={"val":"nil"})
        elif direction == 'insideH':
            self.set_cell_border(cell,start={"val":"nil"})
            self.set_cell_border(cell,end={"val":"nil"})
            self.set_cell_border(cell,top={"val":"nil"})
            self.set_cell_border(cell,bottom={"val":"nil"})
            #self.set_cell_border(cell,insideH={"val":"nil"})
            self.set_cell_border(cell,insizeV={"val":"nil"})
        elif direction == 'insizeV':
            self.set_cell_border(cell,start={"val":"nil"})
            self.set_cell_border(cell,end={"val":"nil"})
            self.set_cell_border(cell,top={"val":"nil"})
            self.set_cell_border(cell,bottom={"val":"nil"})
            self.set_cell_border(cell,insideH={"val":"nil"})
            #self.set_cell_border(cell,insizeV={"val":"nil"})
  

你可能感兴趣的:(python)