简体   繁体   English

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

[英]How to add table border to word doc using python docx

I'm trying to create a word document using docx module of Python.我正在尝试使用 Python 的 docx 模块创建一个 word 文档。 However I am unable to add table border to it.但是我无法为其添加表格边框。

My code is as below:我的代码如下:

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

But it throws error as:但它会抛出错误:

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

Can anyone help me out with this?谁能帮我解决这个问题?

Try with a space:尝试使用空格:

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

I had the same problem and this worked for me.我遇到了同样的问题,这对我有用。

from docx.enum.style import WD_STYLE_TYPE

also add the space to make style='Table Grid'还要加空格使style='Table Grid'

Using space:使用空间:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM