本文整理汇总了Python中docxtpl.DocxTemplate.render方法的典型用法代码示例。如果您正苦于以下问题:Python DocxTemplate.render方法的具体用法?Python DocxTemplate.render怎么用?Python DocxTemplate.render使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类docxtpl.DocxTemplate
的用法示例。
在下文中一共展示了DocxTemplate.render方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DocxTemplate
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
from docxtpl import DocxTemplate
import jinja2
doc = DocxTemplate("TemplateLGULiPADAccountRegistration.docx")
context = { 'Municipality' : "Munishipariti" }
doc.render(context)
doc.save("generated_doc.docx")
示例2: run
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def run(dictionnaire, template, dst):
"""Fonction qui prend en paramètre, le dictionnaire de contenu du fichier
source, un template '.docx' où va être écrit le contenu du dictionnaire
et un chemin de destination où sera enregistré le fichier final.
"""
tpl = DocxTemplate(template)
for fiche in dictionnaire['Fiches']:
for key1, value1 in fiche.iteritems():
if(isinstance(value1, basestring) and
('Exigences' in key1 or 'Pre-requis' in key1)):
value1 = value1.replace('\t', '')
while value1.endswith('\n'):
value1 = value1[:-2]
while value1.startswith('\n'):
value1 = value1[1:]
fiche[key1] = RichText(value1)
elif isinstance(value1, list):
for elem in value1:
for key2, value2 in elem.iteritems():
elem[key2] = RichText(value2)
context = dictionnaire
tpl.render(context)
tpl.save(dst)
示例3: download
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def download(file_type):
'''下载接口'''
if file_type not in ['form','scheme']:abort(404)
id = request.form.get('id')
type = request.form.get('type')
data = query_data(type,id)
#下载策划
if file_type == 'scheme':
if data.filename == 'Nothing':abort(404)
content = send_file(path.join(Upload_path,data.rand_filename))
filename = quote(data.filename)
#if data.applicant!=current_user.name :abort(404)
else :
#生成context并进行渲染
context=make_context(data,type)
for key,value in context.items() :
context[key] = RichText(value)
doc = DocxTemplate(path.join(Docx_path,type+'.docx'))
doc.render(context)
temp_file = path.join(Upload_path,str(current_user.id) +'result.docx')
doc.save(temp_file)
#读取渲染后的文件并将之删除
with open(temp_file,'rb') as f:
content = f.read()
if path.exists(temp_file):
remove(temp_file)
filename = quote(data.association+'-'+types[type][1]+'.docx')
response = make_response(content)
response.headers['Content-Disposition'] = \
"attachment;filename*=UTF-8''" + filename
response.headers['Content-Type'] = 'application/octet-stream'
return response
示例4: gen_a_doc
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def gen_a_doc(doc_name, preparation_module=None):
"""
:param doc_name:
It is a string, that contains a template name to render.
Like if we have a report_template.docx than
to the doc_name should be passed a string 'report_template'
Nota Bene! There is to be a data-cooker. Called the same as the template
For example: report_template.py
And it has to contain a method context(), that returns
a context dictionary for jinja2 rendering engine.
:return:
An file name located in TMP_DEST
"""
if preparation_module is None:
preparation_module = doc_name # WOODOO MAGIC !!!!
DOC_TEMPLATES_DIR = getattr(settings, "DOC_TEMPLATES_DIR", None)
DOC_CONTEXT_GEN_DIR = getattr(settings, "DOC_CONTEXT_GEN_DIR", None)
PROJECT_ROOT = getattr(settings, "PROJECT_ROOT", None)
TMP_DEST = getattr(settings, "TMP_DEST", None)
TMP_URL = getattr(settings, "TMP_URL", None)
doc = DocxTemplate(os.path.join(PROJECT_ROOT, os.path.join(DOC_TEMPLATES_DIR, doc_name + ".docx")))
print(os.path.join(PROJECT_ROOT, os.path.join(DOC_CONTEXT_GEN_DIR, preparation_module)))
context_getter = import_module(preparation_module)
context = getattr(context_getter, "context")()
doc.render(context)
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d_%H:%M:%S")
completeName = os.path.join(TMP_DEST, doc_name + st + ".docx")
doc.save(completeName)
return TMP_URL + doc_name + st + ".docx"
示例5: test_get_env
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def test_get_env(self):
''' 测试 get_env 方法 '''
doc = DocxTemplate(misc.file_open('sell/template/sell.order.docx').name)
data = self.env['sell.order'].search([('name', '=', 'SO00001')])
ctx={'obj':data,'tpl':doc}
jinja_env = report_helper.get_env()
doc.render(ctx,jinja_env)
示例6: import_excel
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def import_excel(self, **post):
fp = StringIO()
datas = post['excel']
if datas:
if re.match(r".*.xls.?",datas.filename):
tmp = datas.stream.read()
if tmp:
ExcelFile = xlrd.open_workbook(filename=datas.filename,file_contents=tmp)
else:
return '请选择要导入的文件'
if ExcelFile:
word_content = []
path = os.path.abspath(os.path.dirname(sys.argv[0]))
tpl = DocxTemplate(path.replace('\\', '/') + '/myaddons/abc_ipt/test_word.docx')
sheet = ExcelFile.sheet_by_index(0)
word_page = []
row_list = []
for i in range(1, sheet.nrows):
for k in range(len(sheet.row(i)),7):
sheet.row(i).append(xlrd.sheet.Cell(""))
row_list = sheet.row(i)
print type(row_list[1])
create_dict = {
'address': row_list[1].value or '',
'department': row_list[2].value or '',
'office': row_list[3].value or '',
'name': row_list[4].value or '',
'numbers': str(int(row_list[5].value)) if row_list[5].value else '',
'mac':str((row_list[6].value)) or ''
}
http.request.env['abc_ipt.ip_phone_importing'].sudo().create(create_dict)
word_page.append(create_dict)
if len(word_page) == 2:
word_content.append(word_page)
word_page = []
continue
if i == sheet.nrows - 1:
word_page.append({
'address': '',
'department': '',
'office': '',
'name': '',
'number': '',
'mac':''
})
word_content.append(word_page)
content = {}
content['info'] = word_content
tpl.render(content)
filename = path.replace('\\', '/') + '/myaddons/abc_ipt/tag.docx'
tpl.save(filename)
return filename
示例7: test
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def test():
"""
演示了如何使用,可以直接执行该文件,但是需要使用自己写的docx模版,和图片
"""
tpl = DocxTemplate("tpls/test_tpl.docx")
#读取图片的数据且使用base64编码
data = open('tpls/python_logo.png','rb').read().encode('base64')
obj={'logo':data}
# 需要添加模版对象
ctx={'obj':obj,'tpl':tpl}
jinja_env = get_env()
tpl.render(ctx,jinja_env)
tpl.save('tpls/test.docx')
示例8: create_source_docx
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def create_source_docx(self, cr, uid, ids, report, context=None):
data = DataModelProxy(self.get_docx_data(cr, uid, ids, report, context))
foldname = os.getcwd()
temp_out_file = os.path.join(foldname, 'temp_out_%s.docx' % os.getpid())
report_stream = ''
doc = DocxTemplate(misc.file_open(report.template_file).name)
doc.render({'obj': data})
doc.save(temp_out_file)
with open(temp_out_file, 'rb') as input_stream:
report_stream = input_stream.read()
os.remove(temp_out_file)
return (report_stream, report.report_type)
示例9: document_creator
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def document_creator(message):
try:
pk = int(message.get('pk').decode())
except ValueError as e:
logger.error(e)
return
try:
poll_result = PollResult.objects.get(pk=pk)
except PollResult.DoesNotExist as e:
logger.error(e)
return
for template in poll_result.poll.templates.objects.all():
doc = DocxTemplate(template.file)
doc.render(poll_result.poll_result)
doc.save()
示例10: memo_docx
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def memo_docx(self, request, pk=None):
rotation_request = get_object_or_404(RotationRequest, pk=pk)
department = rotation_request.requested_department.get_department()
intern = rotation_request.internship.intern
# Check if memo is expected
department_requires_memo = department.requires_memo
if not department_requires_memo:
raise ForwardNotExpected("This rotation request does not require a forward.")
template_name = "inside_request" if department.hospital.is_kamc else "outside_request"
template = DocumentTemplate.objects.get(codename=template_name)
docx = DocxTemplate(template.template_file)
context = {
'now': timezone.now(),
'contact_name': department.contact_name,
'contact_position': department.contact_position,
'hospital': department.hospital.name,
'intern_name': intern.profile.get_en_full_name(),
'specialty': rotation_request.specialty.name,
'month': rotation_request.month.first_day().strftime("%B"),
'year': rotation_request.month.year,
'badge_number': intern.badge_number,
'mobile_number': intern.mobile_number,
'email': intern.profile.user.email,
}
docx.render(context)
docx_file = StringIO.StringIO()
docx.save(docx_file)
docx_file.flush()
docx_file.seek(0)
file_name = "Memo - %s - %s %s" % (
intern.profile.get_en_full_name(),
rotation_request.month.first_day().strftime("%B"),
rotation_request.month.year,
)
response = HttpResponse(
FileWrapper(docx_file),
content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
response['Content-Disposition'] = 'attachment; filename=%s.docx' % file_name
return response
示例11: run
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def run(dico, template, name):
tpl = DocxTemplate(template)
for fiche in dico['Fiches']:
for key1, value1 in fiche.iteritems():
if isinstance(value1, basestring):
# fiche[key1] = RichText(value1)
pass
elif isinstance(value1, list):
for elem in value1:
for key2, value2 in elem.iteritems():
elem[key2] = RichText(value2)
context = dico
tpl.render(context)
tpl.save(name)
示例12: create_source_docx
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def create_source_docx(self, cr, uid, ids, report, context=None):
data = self.get_docx_data(cr, uid, ids, report, context)
foldname = os.getcwd()
temp_out_file = os.path.join(foldname, 'temp_out_%s.docx' % os.getpid())
report_stream = ''
try:
doc = DocxTemplate(misc.file_open(report.template_file).name)
doc.render({'obj': data})
doc.save(temp_out_file)
with open(temp_out_file, 'r') as input_stream:
report_stream = input_stream.read()
except Exception:
raise Exception
finally:
os.remove(temp_out_file)
return (report_stream, report.report_type)
示例13: create_source_docx
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def create_source_docx(self, cr, uid, ids, report, context=None):
data = DataModelProxy(self.get_docx_data(cr, uid, ids, report, context))
tempname = tempfile.mkdtemp()
temp_out_file = self.generate_temp_file(tempname)
doc = DocxTemplate(misc.file_open(report.template_file).name)
#2016-11-2 支持了图片
#1.导入依赖,python3语法
from . import report_helper
#2. 需要添加一个"tpl"属性获得模版对象
doc.render({'obj': data,'tpl':doc},report_helper.get_env())
doc.save(temp_out_file)
if report.output_type == 'pdf':
temp_file = self.render_to_pdf(temp_out_file)
else:
temp_file = temp_out_file
report_stream = ''
with open(temp_file, 'rb') as input_stream:
report_stream = input_stream.read()
os.remove(temp_file)
return report_stream, report.output_type
示例14: convert
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
def convert(self, jira_json):
doc = DocxTemplate(self.templatefile)
context = {}
context["ticketnumber"] = jira_json["key"]
context["priority"] = jira_json["fields"]["priority"]["name"]
context["pref_resolution_date"] = RFCConverter.cleandate(jira_json["fields"]["duedate"])
context["createdate"] = RFCConverter.cleandate(jira_json["fields"]["created"])
context["submitter"] = jira_json["fields"]["creator"]["displayName"]
context["components"] = ", ".join([x["name"] for x in jira_json["fields"]["components"]])
context["submittermail"] = jira_json["fields"]["creator"]["emailAddress"]
context["description"] = R(jira_json["fields"]["description"])
context["accepted_by"] = jira_json["fields"]["creator"]["displayName"]
context["print_date"] = RFCConverter.cleandate()
context["verified_by"] = jira_json["fields"]["creator"]["displayName"]
context["change_number"] = jira_json["key"]
doc.render(context)
target = StringIO()
doc.save(target)
target.seek(0)
name = "RFC_" + jira_json["key"] + ".docx"
return name, target
示例15: MianWindow
# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import render [as 别名]
class MianWindow(noname.MyFrame1):
def __init__(self, master):
super(MianWindow, self).__init__(master)
self.temp_dath = None
self.data_dath = None
self.dir_dath = None
self.desktop = os.path.join(os.path.expanduser('~'), 'Desktop')
self.tempPicker.SetInitialDirectory(self.desktop)
self.dataPicker.SetInitialDirectory(self.desktop)
self.dirPicker.SetInitialDirectory(self.desktop)
self.textShow.WriteText('Welcome to the batch Template software.'+'\n\n')
self.date1 = time.strftime('%Y-%m-%d', time.localtime())
self.time1 = time.strftime('%H-%M-%S', time.localtime())
self.expired = self.loadDate()
self.textShow.WriteText('Data: '+self.date1+'\n')
self.textShow.WriteText('Time: '+self.time1+'\n\n')
self.textShow.WriteText('The software will expire on '+self.expired+'\n\n')
self.textShow.WriteText('')
def loadDate(self):
return '2019-04-30'
def openTempFile(self, event):
if self.date1 > self.expired:
self.textShow.WriteText('The software has expired.\n')
return
self.temp_dath = self.tempPicker.GetPath()
print('Trmplate File:', self.temp_dath)
self.textShow.WriteText('Trmplate File:'+self.temp_dath+"\n")
event.Skip()
def openDataFile(self, event):
if self.date1 > self.expired:
self.textShow.WriteText('The software has expired.\n')
return
self.data_dath = self.dataPicker.GetPath()
print('Data File:', self.data_dath)
self.textShow.WriteText('Data File:'+self.data_dath+"\n")
wookbook = xlrd.open_workbook(self.data_dath)
sheet01 = wookbook.sheet_by_index(0)
self.temp_list = []
if sheet01.nrows > 1:
tt = [i.value for i in sheet01.row(0)]
for i in range(1, sheet01.nrows):
td = [i.value for i in sheet01.row(i)]
self.temp_list.append({k:v for k,v in zip(tt, td)})
event.Skip()
def openDataDir(self, event):
if self.date1 > self.expired:
self.textShow.WriteText('The software has expired.\n')
return
self.dir_dath = self.dirPicker.GetPath()
self.textShow.WriteText('Saved Dir:'+self.dir_dath+"\n")
print('Saved Dir:', self.dir_dath)
event.Skip()
def startButtonFunc( self, event ):
if self.date1 > self.expired:
self.textShow.WriteText('The software has expired.\n')
return
if self.temp_dath == None or len(self.temp_dath) == 0:
self.textShow.WriteText('Please choice a template file.\n')
return
if self.data_dath == None or len(self.data_dath) == 0:
self.textShow.WriteText('Please choice a data file.\n')
return
if self.dir_dath == None or len(self.dir_dath) == 0:
self.textShow.WriteText('Please choice a destination folder.\n')
return
print(f'Batch Deal Start: Total {len(self.temp_list)}')
listlen = len(self.temp_list)
for i in range(100):
if i < listlen:
v = (i+1)*100/listlen
v = v if 0 <= v <= 100 else 100
self.gauge.SetValue(v)
self.doc = DocxTemplate(self.temp_dath)
dtmp = self.temp_list[i]
tname = str([i for i in dtmp.values()][0]) +'.docx'
self.doc.render(dtmp)
name = os.path.join(self.dir_dath, tname)
print('Create File:', name)
self.textShow.WriteText('Create File:'+name+"\n");
self.doc.save(name)
print('Batch Deal End')