python创建word表格_如何添加表格边框到Word文档使用Python Docx

编程知识 行业动态 更新时间:2024-06-13 00:17:41

我想创建一个Word文档使用Python的docx模块。 但是我无法为它添加表格边框。如何添加表格边框到Word文档使用Python Docx

我的代码如下:

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

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'"

谁能帮我这个?

+1

确保您的文档中读取这个页面和一个紧随其后(使用下一页按钮):http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html –

+0

谢谢我试过 –

+1

它工作正常,并创建了所需的文档。我将表格网格添加到模板中,并将其删除并保存。工作正常。唯一的事情是每次都显示一条警告消息。 警告消息如下: “文件”C:\ Users \ Vinny \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ site-packages \ docx \ styles \ styles.py“,第54行 警告(msg,UserWarning) UserWarning:不推荐使用style_id的样式查找,而是使用样式名称作为关键字.s:“ –

更多推荐

python创建word表格_如何添加表格边框到Word文档使用Python Docx

本文发布于:2023-03-25 14:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/ba52bfd28351f4aff77df88a5b3bbb3e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表格   边框   文档   word   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!