表格样式KeyError:u“没有带名称的样式'表格网格'”

时间:2018-06-04 19:39:43

标签: python python-docx

我试图通过python-docx插入一个表,但它给出了错误 代码是:

#-*-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()    

总是给我错误的是:

  

Traceback(最近一次调用最后一次):文件   “C:\ Users \ Robin-work-laptop \ Desktop \ New folder \ log \ makereport.py”,   第49行,在       buildtable()文件“C:\ Users \ Robin-work-laptop \ Desktop \ New folder \ log \ makereport.py”,第41行,在buildtable中       table.style ='表格网格'文件“C:\ Python27 \ lib \ site-packages \ docx \ table.py”,第134行,样式       style_or_name,WD_STYLE_TYPE.TABLE文件“C:\ Python27 \ lib \ site-packages \ docx \ parts \ _ document.py”,第76行,in   get_style_id       return self.styles.get_style_id(style_or_name,style_type)文件“C:\ Python27 \ lib \ site-packages \ docx \ styles \ styles.py”,第113行,in   get_style_id       return self._get_style_id_from_name(style_or_name,style_type)文件“C:\ Python27 \ lib \ site-packages \ docx \ styles \ styles.py”,第143行,   在_get_style_id_from_name中       return self._get_style_id_from_style(self [style_name],style_type)文件“C:\ Python27 \ lib \ site-packages \ docx \ styles \ styles.py”,第57行,   在 getitem       引发KeyError(“没有名称为'%s'的样式'”%key)KeyError:u“没有名称为'Table Grid'的样式”

请帮助我阅读列表中的样式作为表格网格

的文档

1 个答案:

答案 0 :(得分: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