'How to make cell borders of table with python-docx

I want to setup cell borders with python-docx. I used the follow command, but error happens.

document = Document("mydoc.docx")
table = document.add_table(rows=1, cols=3, style='Table Grid')

The error is as follows;

KeyError: "no style with name 'TableGrid'"


Solution 1:[1]

you cannot use Table Grid because the document does not have that style in it

alternately you can work on oxml level and add the border element to the tableProperty elment

import docx
document = docx.Document()
table = document.add_table(2,2)
borders = table._tbl.tblPr.get_or_add_tblBorders()
bottom_border = docx.oxml.shared.OxmlElement('w:bottom')
bottom_border.set(docx.oxml.shared.qn('w:val'), 'single')
bottom_border.set(docx.oxml.shared.qn('w:sz'), '4')
borders.append(bottom_border)
document.save('test.docx')


and similarly, you can do the same for the top, left, right borders

Solution 2:[2]

This error indicates there is no "Table Grid" style in "mydoc.docx".

You can read more about latent styles and styles in general and there behaviors (such as this) in the documentation here:
https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html

and here:
https://python-docx.readthedocs.io/en/latest/user/styles-using.html

Basically you need to:

  1. open "mydoc.docx" with Word
  2. add a table
  3. apply the "Table Grid" table style to the new table
  4. delete the table
  5. save the file (as the same name)

This will add the "Table Grid" style to that docx file and then your code should work as expected.

Solution 3:[3]

@Obay Dabba get_or_add_tblBorders doesn't seem to be a method anymore, but I was able to get this to work with:

borders = OxmlElement('w:tblBorders')
bottom_border = OxmlElement('w:bottom')
bottom_border.set(qn('w:val'), 'single')
bottom_border.set(qn('w:sz'), '4')
borders.append(bottom_border)
table._tbl.tblPr.append(borders)

Solution 4:[4]

I think you have types wrong on line:

table = document.add_table(rows=1, cols=3, style='Table Grid')

updated line:

table = document.add_table(rows=1, cols=3, style='TableGrid')

or else table.style = 'TableGrid'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Obay Daba
Solution 2 scanny
Solution 3 Jayme Gordon
Solution 4 buddemat