使用python操作word模板創建表格不成功,報錯:
KeyError: u"no style with name 'Table Grid'"
附上一段代碼:
# coding=utf8
from docxtpl import DocxTemplate
import docx
tmp = DocxTemplate('D:/git/test.docx')
table = tmp.add_table(rows=1, cols=6, style='Table Grid')
hdr_cells = table.rows[0].cells
hdr_cells[0].text = u'姓名'
hdr_cells[1].text = u'性別'
hdr_cells[2].text = u'專業班級'
hdr_cells[3].text = u'學號'
報錯是這樣的:
Traceback (most recent call last):
File "D:/git/test.py", line 7, in <module>
table = tmp.add_table(rows=1, cols=6, style='Table Grid')
File "D:\Program Files\python2.7\lib\site-packages\docx\document.py", line 100, in add_table
table.style = style
File "D:\Program Files\python2.7\lib\site-packages\docx\table.py", line 134, in style
style_or_name, WD_STYLE_TYPE.TABLE
File "D:\Program Files\python2.7\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 "D:\Program Files\python2.7\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 "D:\Program Files\python2.7\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 "D:\Program Files\python2.7\lib\site-packages\docx\styles\styles.py", line 57, in __getitem__
raise KeyError("no style with name '%s'" % key)
KeyError: u"no style with name 'Table Grid'"
這個報錯賊難受,當初各種找錯,一個師兄的工程又能跑起來,偏偏我的工程會報錯。各種嘗試,最後發現師兄的代碼改一下拉到我的工程也不能行,把我的代碼換過去又可以運行,於是把師兄工程裏的word模板拉到我的工程居然就能運行了
解決方法:
我的office是出廠自帶的2016家庭學生版,使用另一個也是出場自帶office的創建的office也沒成功。而師兄電腦上的是KMS激活的standard版。解決方法就是用standard創建一個word,拉到工程裏邊。可以複製,可以用家庭學生版修改,源文件不能是家庭學生版創建的