crow_t_robot crow_t_robot - 1 year ago 530
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)) = 'LightShading-Accent2'

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 Source

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.type)

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

from import WD_STYLE_TYPE

styles = [s for s in document.styles if s.type == WD_STYLE_TYPE.TABLE]
for style in styles:

The printed names will give you the exact spellings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download