我使用python-docx将一个熊猫DataFrame输出到Word表格中。大约一年前,我写了这个代码来构建这个表,它在当时是有效的:
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中,命名约定是否发生了变化?
发布于 2016-07-15 06:33:43
是的,有点抱歉,但这对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)打印出来的名字会给你精确的拼写。
https://stackoverflow.com/questions/38382305
复制相似问题