如何使用Python docx为Word文档添加表格边框

4
我是一名有帮助的助手,以下是翻译的结果:

我正在尝试使用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'"

有人能帮我解决这个问题吗?


1
请确保您阅读了文档中的此页面以及紧随其后的页面(使用“下一页”按钮):http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html - scanny
1
它正常工作并创建了所需的文档。我将表格网格添加到模板中,删除并保存它。一切正常,唯一的问题是每次都会显示警告消息。警告消息如下:“File”C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py”, line 54 警告(MSG,UserWarning) UserWarning:按style_id查找样式已弃用。改用样式名称作为密钥。s:“ - Marvin
剩下的堆栈跟踪是什么? - scanny
1
@VinnyKaur 请查看此链接以解决您的警告问题:https://dev59.com/4Ijca4cB1Zd3GeqPzJ3t - Maruti Mohanty
啊!我检查了一下,它起作用了,谢谢@MarutiMohanty。 - Marvin
这个回答解决了你的问题吗?使用python-docx指定表格边框外观 - JustCarty
3个回答

8

尝试添加空格:

table = doc.add_table(rows = 4, cols = 2, style='Table Grid')

我曾遇到同样的问题,这个方法对我有用。


0
from docx.enum.style import WD_STYLE_TYPE

同时添加空格以使style='Table Grid'


@AhmedMamdouh 你认为它不起作用的原因是什么?对我来说,它绝对有效,还有其他几个回答了这个问题的人也是这样。 - Zenon Anderson

0

使用空格:

table = document.add_table(rows=1, cols=3, style='Table Grid')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接