我试图通过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()
它总是给我错误是:
回溯(最近一次调用最后一次):文件“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 ='Table Grid'File”C:\ Python27 \ lib \ site-packages \ docx \ table.py“,line 134,样式style_or_name,WD_STYLE_TYPE.TABLE文件“C:\ Python27 \ lib \ site-packages \ docx \ parts \ _ document.py”,第76行,在get_style_id中返回self.styles.get_style_id(style_or_name,style_type)文件“C :\ Python27 \ lib \ site-packages \ docx \ styles \ styles.py“,第113行,在get_style_id中返回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中返回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'的样式”
请帮助我阅读列表中样式的documnets作为表格
1 回答
您的文档中没有定义“表格网格”样式 . Word中“内置”的样式实际上直到第一次使用时才会添加到文档中 .
您可以通过阅读
python-pptx
文档的相关部分来了解有关这些所谓"latent styles"的行为的更多信息:http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
和这里:
http://python-docx.readthedocs.io/en/latest/user/styles-using.html