2017-04-23 1057 views
2

我想创建一个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 <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

+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:“ –

回答

0

尝试用空间:table = doc.add_table(rows = 4, cols = 2, style='Table Grid')

我有同样的问题,这为我工作。

0

从docx.enum.style进口WD_STYLE_TYPE

还添加了空间,使风格=“表网格”