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'"
誰能幫我這個?
確保您的文檔中讀取這個頁面和一個緊隨其後(使用下一頁按鈕):http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html – scanny
謝謝我試過 –
它工作正常,並創建了所需的文檔。我將表格網格添加到模板中,並將其刪除並保存。工作正常。唯一的事情是每次都顯示一條警告消息。 警告消息如下: 「文件」C:\ Users \ Vinny \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ site-packages \ docx \ styles \ styles.py「,第54行 警告(msg,UserWarning) UserWarning:不推薦使用style_id的樣式查找,而是使用樣式名稱作爲關鍵字.s:「 –