Python-docx样式格式
Python-docx style format
我正在使用 python-docx 将 Pandas DataFrame 输出到 Word table。大约一年前,我编写了这段代码来构建当时有效的 table:
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 的新版本中的命名约定是否发生了变化?
是的,有点抱歉,但这是 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)
如果你想缩小一点,比如只有 table 样式,你可以添加:
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)
打印出来的名字会给你准确的拼写。
我正在使用 python-docx 将 Pandas DataFrame 输出到 Word table。大约一年前,我编写了这段代码来构建当时有效的 table:
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 的新版本中的命名约定是否发生了变化?
是的,有点抱歉,但这是 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)
如果你想缩小一点,比如只有 table 样式,你可以添加:
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)
打印出来的名字会给你准确的拼写。