crow_t_robot crow_t_robot - 4 months ago 96
Python Question

Python-docx style format

I am using python-docx to output a Pandas DataFrame to a Word table. About a year ago, I wrote this code to build that table, which worked at the time:

table = Rpt.add_table(rows=1, cols=(df.shape[1]+1))
table.style = 'LightShading-Accent2'


Where
Rpt
is a Document from a template. Now, I get an error:

KeyError: "no style with name 'LightShading-Accent2'"


How should I go about defining the style? Has the naming convention changed in newer versions of python-docx?

Answer

Yes, slightly, apologies for that, but it was the right long-term decision for the API.

Try using "Light Shading - Accent 2" instead. It should be the name just as it appears in the Word user interface (UI).

If you still can't get it, you can enumerate all the style names with something like this:

from docx import Document

document = Document()
styles = document.styles
for style in styles:
    print "'%s' -- %s" % (style.name, style.type)

If you want to narrow it down a bit, say to only table styles, you can add this:

from docx.enum.style import WD_STYLE_TYPE

styles = [s for s in document.styles if s.type == WD_STYLE_TYPE.TABLE]
for style in styles:
    print(style.name)

The printed names will give you the exact spellings.

Comments