table style KeyError: u“no style with name 'Table Grid'”

眉间皱痕 提交于 2020-01-16 08:55:19

问题


I trying to insert a table via python-docx but it give the error code is:

#-*-coding:utf-8-*-
import re 
import time
import datetime
import sys
import os
import csv
from docx import Document
import docx
from docx import *  
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.shared import Cm
from docx import section
from docx.enum.table import WD_TABLE_ALIGNMENT
import win32com.client

lastday=str(datetime.date.today()-datetime.timedelta(days=1))

CURRENT_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))

docxFilePath = os.path.join(CURRENT_DIR,'logsample.docx')
doc=Document(docxFilePath)



def buildtable():


    #id_numbers=sum(1 for row in idlist)

    table = doc.add_table(rows = 3, cols = 2)


    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.style = 'Table Grid'







buildtable()    

it always gives me error is :

Traceback (most recent call last): File "C:\Users\Robin-work-laptop\Desktop\New folder\log\makereport.py", line 49, in buildtable() File "C:\Users\Robin-work-laptop\Desktop\New folder\log\makereport.py", line 41, in buildtable table.style = 'Table Grid' File "C:\Python27\lib\site-packages\docx\table.py", line 134, in style style_or_name, WD_STYLE_TYPE.TABLE File "C:\Python27\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:\Python27\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:\Python27\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:\Python27\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'"

Please help I read the documnets the style is in the list as Table Grid


回答1:


Your document does not have the 'Table Grid' style defined in it. The styles that appear to be "built-in" in Word are actually not added to the document until the first time they are used.

You can learn more about the behavior of these so-called "latent styles" by reading the related part of the python-pptx documentation here:
http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
and here:
http://python-docx.readthedocs.io/en/latest/user/styles-using.html



来源:https://stackoverflow.com/questions/50687678/table-style-keyerror-uno-style-with-name-table-grid

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