I need to setup cells borders in table with python-docx, but can't find how to. Please help.
            Asked
            
        
        
            Active
            
        
            Viewed 3.4k times
        
    20
            
            
        - 
                    1Have you checked: https://github.com/python-openxml/python-docx/issues/9? – agold Oct 12 '15 at 09:15
 
3 Answers
24
            
            
        table = document.add_table(rows, cols)
table.style = 'Table Grid'
using style with TableGrid as style ID is deprecated. Now we need to use name hence:
table.style = 'Table Grid'
        ncica
        
- 7,015
 - 1
 - 15
 - 37
 
        Satish Roddom
        
- 241
 - 2
 - 4
 
16
            
            
        Here is the snippet, I used in one of my projects. Works with merged cells too.
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def set_cell_border(cell: _Cell, **kwargs):
    """
    Set cell`s border
    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        start={"sz": 24, "val": "dashed", "shadow": "true"},
        end={"sz": 12, "val": "dashed"},
    )
    """
    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]))
Check http://officeopenxml.com/WPtableBorders.php for available attributes values
        MadisonTrash
        
- 5,444
 - 3
 - 22
 - 25
 
- 
                    2When I open using google docs, the side borders don't show up. Works for libre office though. – Tharun M Mar 31 '21 at 12:02
 
15
            
            
        Take a look at the issue posted on git.
You can use some default table style:
table = document.add_table(rows, cols)
table.style = 'TableGrid'
        Iulian Stana
        
- 1,632
 - 1
 - 14
 - 17
 
- 
                    5UserWarning: style lookup by style_id is deprecated. Use style name as key instead. return self._get_style_id_from_style(self[style_name], style_type) – dEll Oct 31 '18 at 11:34