2016-07-14 180 views
0

我正在使用python-docx将Pandas DataFrame输出到Word表格。大约一年前,我写了这个代码构建表,这在当时的工作:Python-docx样式格式

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

哪里Rpt为模板的文档。现在,我收到一个错误:

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

我应该如何定义样式?在python-docx的新版本中命名约定是否已更改?

回答

1

是的,有点道歉,但这是API的长期正确决策。

尝试使用“Light Shading - Accent 2”代替。它应该是它出现在Word用户界面(UI)中的名称。

如果仍然不能得到它,你可以像这样枚举所有样式名称:

from docx import Document 

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

如果你想将它缩小了一点,说只表样式,可以加上:

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) 

打印的名称会给你确切的拼写。

+0

我仍然得到相同的错误:KeyError:“没有名称为'Light Shading - Accent 2'的样式”。在Python 3.5.1上使用0.8.5版 –

+0

当您按照我提到的方式枚举样式名称时,是否在列表中找到该样式? – scanny

+0

我没有 - 第二个片段只有两种风格,“正常表格”和“表格网格”。我检查了模板,并且可以使用所有常用的Word默认表格 –