2016-07-14 79 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默認表格 –