How to add table border to word doc using python docx

大兔子大兔子 提交于 2020-02-24 04:41:07

问题


I'm trying to create a word document using docx module of Python. 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?


回答1:


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.




回答2:


from docx.enum.style import WD_STYLE_TYPE

also add the space to make style='Table Grid'




回答3:


Using space:

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


来源:https://stackoverflow.com/questions/43567448/how-to-add-table-border-to-word-doc-using-python-docx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!