【发布时间】:2017-04-23 04:39:34
【问题描述】:
我正在尝试使用 Python 的 docx 模块创建一个 word 文档。 但是我无法为其添加表格边框。
我的代码如下:
import docx
from docx import Document
from docx.shared import Pt
doc = Document('C:/Users/Vinny/Desktop/Python/Template.docx')
doc.add_paragraph('Changes:')
doc.add_paragraph('Metrics:')
#add table
table = doc.add_table(rows = 4, cols = 2, style='TableGrid')
doc.save('C:/Users/Vinny/Desktop/Python/rel.docx')
但它会抛出错误:
Traceback (most recent call last):
File "C:\Users\Vinny\Desktop\Python\abc.py", line 14, in <module>
table = doc.add_table(rows = 4, cols = 2, style='TableGrid')
File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\document.py", line 100, in add_table
table.style = style
File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\table.py", line 134, in style
style_or_name, WD_STYLE_TYPE.TABLE
File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\parts\document.py", line 76, in get_style_id
return self.styles.get_style_id(style_or_name, style_type)
File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 113, in get_style_id
return self._get_style_id_from_name(style_or_name, style_type)
File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 143, in _get_style_id_from_name
return self._get_style_id_from_style(self[style_name], style_type)
File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 57, in __getitem__
raise KeyError("no style with name '%s'" % key)
KeyError: "no style with name 'TableGrid'"
谁能帮我解决这个问题?
【问题讨论】:
-
确保您阅读了文档中的这一页以及紧随其后的那一页(使用“下一步”按钮):python-docx.readthedocs.io/en/latest/user/…
-
它工作正常并创建了所需的文档。我在模板中添加了表格网格,删除并保存了它。工作正常。唯一的事情是每次都显示一条警告消息。警告消息类似于:“文件“C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py”,第 54 行警告(msg,UserWarning)用户警告:不推荐使用 style_id 查找样式。请改用样式名称作为键。s : "
-
堆栈跟踪的其余部分是什么?
-
@VinnyKaur 检查此链接以修复您的警告stackoverflow.com/questions/28973277/…
-
啊!我检查了一下,它起作用了,谢谢@MarutiMohanty。
标签: python python-3.x docx python-docx