本文整理汇总了Python中docxtpl.DocxTemplate类的典型用法代码示例。如果您正苦于以下问题:Python DocxTemplate类的具体用法?Python DocxTemplate怎么用?Python DocxTemplate使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DocxTemplate类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dir
# -*- coding: utf-8 -*-
'''
Created : 2017-05-19
@author: Eric Lapouyade
'''
from docxtpl import DocxTemplate
tpl=DocxTemplate(r'C:/Users/nantian/Desktop/resume_template.docx')
context = {
'name': 'linana',
'gender':'female',
'birthday':'19920520',
'items' : [
{'desc' : 'Python interpreters', 'qty' : 2, 'price' : 'FREE' },
{'desc' : 'Django projects', 'qty' : 5403, 'price' : 'FREE' },
{'desc' : 'Guido', 'qty' : 1, 'price' : '100,000,000.00' },
],
'in_europe' : True,
'is_paid': False,
'company_name' : 'The World Wide company',
'total_price' : '100,000,000.00'
}
tpl.render(context)
print dir(tpl.docx)
# tpl.save('C:/Users/nantian/Desktop/
示例2: DocxTemplate
from docxtpl import DocxTemplate
import jinja2
doc = DocxTemplate("TemplateLGULiPADAccountRegistration.docx")
context = { 'Municipality' : "Munishipariti" }
doc.render(context)
doc.save("generated_doc.docx")
示例3: run
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)
示例4: gen_a_doc
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: download
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
示例6: test_get_env
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)
示例7: export_to_word
def export_to_word(self,**kargs):
filename = kargs['filename']
path = os.path.abspath(os.path.dirname(sys.argv[0]))
file = DocxTemplate(filename)
# file = docx.Document(path.replace('\\', '/') +'/'+filename)
fp = StringIO()
file.save(fp)
return request.make_response(fp.getvalue(),
headers=[('Content-Disposition', content_disposition('标签.docx')),
('Content-Type', 'application/vnd.ms-word')],
)
示例8: import_excel
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
示例9: test
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')
示例10: create_source_docx
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)
示例11: startButtonFunc
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')
示例12: document_creator
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()
示例13: memo_docx
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
示例14: run
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)
示例15: create_source_docx
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)