我可以在.docx文件的末尾添加一个表,但是我有一个.docx模板,并且不能在文本之间添加表。
我使用字典(context)将要插入的主要信息保存到.docx,但是我需要在.docx文件中的特殊空间(标记为{{variable}})中添加包含一些信息的表。我尝试将“表格”-变量添加到上下文:context [“ tableplace”] = table
但这没用
from docxtpl import DocxTemplate
from docx import Document
from docx.styles.style import _TableStyle
from docx.shared import Inches
class Client:
def __init__(self,name,data,pasport,valid):
self.name = name
self.data = data
self.pasport = pasport
self.valid = valid
doc = DocxTemplate("Template2019.docx")
context = {
'persons' : "3", #number of people
'from' : "11.22.33", # date
'till' : "22.22.33", # arrival date
'nights' : "11",
'air1' : "Air",
'air2' : "Air",
'flight' : "My departure", #flight
'flight_back' : "My departure",
'hotel' : "Smth",
'number' : "12345",
'feed' : "AI",
'days' : "12",
}
per = int('3') #number of persons
records=[] #List of clients info
for objs in range(per):
print('Client ', objs+1)
name = input('\tName : ')
data = input('\tData : ')
pasport = input('\tPasport : ')
valid = input('\tValid : ')
records.append(Client(name,data,pasport,valid))
print(objs)
# add table ------------------
table = doc.add_table(1, cols=4)
table.style = 'Table Grid'
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Data of Birhtday'
hdr_cells[2].text = 'Pasport'
hdr_cells[3].text = 'valid until'
for i in range(per):
row_cells = table.add_row().cells
row_cells[0].text = records[i].name
row_cells[1].text = records[i].data
row_cells[2].text = records[i].pasport
row_cells[3].text = records[i].valid
doc.render(context)
doc.save("app/try.docx")
我想在代替标记的文档中看到一张表格