Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup cell borders with python-docx

I need to setup cells borders in table with python-docx, but can't find how to. Please help.

like image 319
Valentin Avatar asked Oct 11 '15 20:10

Valentin


People also ask

How do I read a table from Docx in Python?

Process the table data to pandas dataframe. Using the in-built attributes of python-docx library, read each rows of the table and retrieve the text from each cells and create python list of list containing each row. Then convert that python data structure to pandas DataFrame.

Can we apply border to a cell in a table?

Click the Borders arrow > Line Color arrow, and then pick a color. Click the Borders arrow > Line Style arrow, and then pick a line style. Select cells you want to draw borders around.


2 Answers

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'

like image 183
Satish Roddom Avatar answered Sep 21 '22 11:09

Satish Roddom


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

like image 34
MadisonTrash Avatar answered Sep 19 '22 11:09

MadisonTrash