如何使用python docx将表格边框添加到word doc

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

谁能帮我这个忙吗?

解决方法:

尝试一个空格:table = doc.add_table(rows = 4,cols = 2,style =’Table Grid’)

我有同样的问题,这对我有用.

上一篇:thinkphp PHPWord数据导出word固定模板,ZipArchive文件批量压缩打包下载


下一篇:数字集成电路设计经验技巧分享