使用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,拉到工程里边。可以复制,可以用家庭学生版修改,源文件不能是家庭学生版创建的