from docxtpl import DocxTemplate import jinja2 doc = DocxTemplate("TemplateLGULiPADAccountRegistration.docx") context = { 'Municipality' : "Munishipariti" } doc.render(context) doc.save("generated_doc.docx")
# -*- 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/
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)
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
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"
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)
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')], )
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
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')
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)
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')
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()
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
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)
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)
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
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
# -*- coding: utf-8 -*- ''' Created : 2016-03-26 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/nested_for_tpl.docx') context = { 'dishes' : [ {'name' : 'Pizza', 'ingredients' : ['bread','tomato', 'ham', 'cheese']}, {'name' : 'Hamburger', 'ingredients' : ['bread','chopped steak', 'cheese', 'sauce']}, {'name' : 'Apple pie', 'ingredients' : ['flour','apples', 'suggar', 'quince jelly']}, ], 'authors' : [ {'name' : 'Saint-Exupery', 'books' : [ {'title' : 'Le petit prince'}, {'title' : "L'aviateur"}, {'title' : 'Vol de nuit'}, ]}, {'name' : 'Barjavel', 'books' : [ {'title' : 'Ravage'}, {'title' : "La nuit des temps"}, {'title' : 'Le grand secret'}, ]}, ] }
# -*- coding: utf-8 -*- ''' Created : 2017-01-14 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate, InlineImage # for height and width you have to use millimeters (Mm), inches or points(Pt) class : from docx.shared import Mm, Inches, Pt tpl=DocxTemplate('test_files/inline_image_tpl.docx') context = { 'myimage' : InlineImage(tpl,'test_files/python_logo.png',width=Mm(20)), 'myimageratio': InlineImage(tpl, 'test_files/python_jpeg.jpg', width=Mm(30), height=Mm(60)), 'frameworks' : [{'image' : InlineImage(tpl,'test_files/django.png',height=Mm(10)), 'desc' : 'The web framework for perfectionists with deadlines'}, {'image' : InlineImage(tpl,'test_files/zope.png',height=Mm(10)), 'desc' : 'Zope is a leading Open Source Application Server and Content Management Framework'}, {'image': InlineImage(tpl, 'test_files/pyramid.png', height=Mm(10)), 'desc': 'Pyramid is a lightweight Python web framework aimed at taking small web apps into big web apps.'}, {'image' : InlineImage(tpl,'test_files/bottle.png',height=Mm(10)), 'desc' : 'Bottle is a fast, simple and lightweight WSGI micro web-framework for Python'}, {'image': InlineImage(tpl, 'test_files/tornado.png', height=Mm(10)), 'desc': 'Tornado is a Python web framework and asynchronous networking library.'},
#!/usr/bin/env python import json import sys from docxtpl import DocxTemplate doc = DocxTemplate("order-template.docx") context = json.load(open(sys.argv[1])) doc.render(context) doc.save(sys.argv[1].replace(".json", ".docx")) #print(list(context['fields'].keys())) #print(list(context.keys()))
#!/usr/bin/env python from docxtpl import DocxTemplate import jinja2 import subprocess doc = DocxTemplate("invite.docx") context = { 'title' : "Lord Commander", 'name' : "John Snow" } jinja_env = jinja2.Environment() # jinja_env.filters['myfilter'] = myfilterfunc doc.render(context,jinja_env) filename = "JohnSnow.docx" doc.save(filename) #unoconv -f pdf invite.docx out = subprocess.check_output(['/usr/bin/python3', '/usr/bin/unoconv', '-f', 'pdf', 'invite.docx']) print out
def __init__(self, args): self.template_filename = args.TEMPLATE_FILE self.template = DocxTemplate(args.TEMPLATE_FILE) self.report = args.REPORT_FILE self.ua_csv = args.UA_CSV
def gerate_report(data: dict): template = DocxTemplate("media/template/template.docx") context = data template.render(context) template.save(result_path)
import json from docxtpl import DocxTemplate doc = DocxTemplate("report_tpl_5_x.docx") with open('ds.json', 'r') as f: data = json.load(f) doc.render(data) doc.save("generated_doc.docx")
def odp2(request): name_spolka_do_analizy_ver1 = request.GET["spółka_do_analizy_ver1"] name_spolka_do_analizy_ver2 = request.GET["spółka_do_analizy_ver2"] name2 = str(szukanie(name_spolka_do_analizy_ver2)) name1 = str(szukanie(name_spolka_do_analizy_ver1)) if (name1 != 'None'): flaga = True else: flaga = False if (name2 != 'None'): flaga = True else: flaga = False if flaga == True: www_ver1 = 'https://stooq.pl/q/d/l/?s=' + name1 + '&i=d' www_ver2 = 'https://stooq.pl/q/d/l/?s=' + name2 + '&i=d' odp1 = download(www_ver1, name1) odp2 = download(www_ver2, name2) dane1 = pd.read_csv(odp1, sep=',', na_values=" ").dropna() dane2 = pd.read_csv(odp2, sep=',', na_values=" ").dropna() a = dane1 b = dane2 all_Data1 = [] all_Data2 = [] for i in range(a.shape[0]): temp = a.iloc[i] all_Data1.append(dict(temp)) for i in range(b.shape[0]): temp = b.iloc[i] all_Data2.append(dict(temp)) baza = Nazwy_spółek.objects.all() top = Popular.objects.all() context = { 'flaga': flaga, 'data': baza, 'name1': name1, 'name2': name2, 'top': top, } if (flaga == True): del all_Data1[-1] del all_Data2[-1] ver1 = Nazwy_spółek.objects.get(spolka_data_skrot=name1) ver2 = Nazwy_spółek.objects.get(spolka_data_skrot=name2) for data in all_Data1: if Dane_spółek.objects.filter( spolka_name=ver1, spolka_data=data["b'Data"]).exists() == False: Dane_spółek.objects.create( spolka_name=ver1, spolka_otwarcie=data['Otwarcie'], spolka_najwyzszy=data['Najwyzszy'], spolka_najnizszy=data['Najnizszy'], spolka_zamkniecie=data['Zamkniecie'], spolka_data=data["b'Data"]) for data in all_Data2: if Dane_spółek.objects.filter( spolka_name=ver2, spolka_data=data["b'Data"]).exists() == False: Dane_spółek.objects.create( spolka_name=ver2, spolka_otwarcie=data['Otwarcie'], spolka_najwyzszy=data['Najwyzszy'], spolka_najnizszy=data['Najnizszy'], spolka_zamkniecie=data['Zamkniecie'], spolka_data=data["b'Data"]) dane_1 = Dane_spółek.objects.all().filter(spolka_name=ver1) dane_2 = Dane_spółek.objects.all().filter(spolka_name=ver2) # ///////////////////// Mx1 = srednia(dane1['Otwarcie']) My1 = timesrednia(len(dane1)) # My1 = srednia(dane1) Mx2 = srednia(dane2['Otwarcie']) My2 = timesrednia(len(dane2)) # My1 = srednia(dane1) Sx1 = odchylenie(dane1['Otwarcie'], Mx1) Sy1 = odchylenieczas(len(dane1), My1) Sx2 = odchylenie(dane2['Otwarcie'], Mx2) Sy2 = odchylenieczas(len(dane2), My2) # n = len(dane1['Otwarcie']) # vr = pd.DataFrame(dane1[:]) # vry2 = sumowanie2(len(dane1)) # vrxy = sumowanie(len(dane1), dane1['Otwarcie']) # vrx2 = dane1['Otwarcie'] * dane1['Otwarcie'] # sumx = dane1['Otwarcie'].sum() today = date.today() dane_akt_1 = Dane_spółek.objects.all().filter( spolka_name=ver1, spolka_data__year=today.year - 1) dane_akt_2 = Dane_spółek.objects.all().filter( spolka_name=ver2, spolka_data__year=today.year - 1) flaga20 = False flaga19 = False flaga18 = False if Dane_spółek.objects.filter( spolka_name=ver1, spolka_data__year='2020').exists() == True: dane_2020 = Dane_spółek.objects.all().filter( spolka_name=ver1, spolka_data__year='2020') flaga20 = True if Dane_spółek.objects.filter( spolka_name=ver1, spolka_data__year='2019').exists() == True: dane_2019 = Dane_spółek.objects.all().filter( spolka_name=ver1, spolka_data__year='2019') flaga19 = True if Dane_spółek.objects.filter( spolka_name=ver1, spolka_data__year='2018').exists() == True: dane_2018 = Dane_spółek.objects.all().filter( spolka_name=ver1, spolka_data__year='2018') flaga18 = True flaga20s = False flaga19s = False flaga18s = False if Dane_spółek.objects.filter( spolka_name=ver2, spolka_data__year='2020').exists() == True: dane_2020_2 = Dane_spółek.objects.all().filter( spolka_name=ver2, spolka_data__year='2020') flaga20s = True if Dane_spółek.objects.filter( spolka_name=ver2, spolka_data__year='2019').exists() == True: dane_2019_2 = Dane_spółek.objects.all().filter( spolka_name=ver2, spolka_data__year='2019') flaga19s = True if Dane_spółek.objects.filter( spolka_name=ver2, spolka_data__year='2018').exists() == True: dane_2018_2 = Dane_spółek.objects.all().filter( spolka_name=ver2, spolka_data__year='2018') flaga18s = True # dane_2020 = Dane_spółek.objects.all().filter(spolka_name=ver1, spolka_data__year='2020') # dane_2019 = Dane_spółek.objects.all().filter(spolka_name=ver1, spolka_data__year='2019') # dane_2018 = Dane_spółek.objects.all().filter(spolka_name=ver1, spolka_data__year='2018') if (flaga20 == True): sum2020 = dane_2020.count() op2020 = dane_2020.aggregate(Sum('spolka_najwyzszy')) op20202 = dane_2020.aggregate(Sum('spolka_najnizszy')) ost = (op2020['spolka_najwyzszy__sum'] - op20202['spolka_najnizszy__sum']) / sum2020 else: ost = 0 if (flaga19 == True): sum1 = dane_2019.count() op1 = dane_2019.aggregate(Sum('spolka_najwyzszy')) op2 = dane_2019.aggregate(Sum('spolka_najnizszy')) kk = (op1['spolka_najwyzszy__sum'] - op2['spolka_najnizszy__sum']) / sum1 else: kk = 0 if (flaga18 == True): sum8 = dane_2018.count() op8 = dane_2018.aggregate(Sum('spolka_najwyzszy')) op81 = dane_2018.aggregate(Sum('spolka_najnizszy')) k8 = (op8['spolka_najwyzszy__sum'] - op81['spolka_najnizszy__sum']) / sum8 else: k8 = 0 # dane_2020_2 = Dane_spółek.objects.all().filter(spolka_name=ver2, spolka_data__year='2020') # dane_2019_2 = Dane_spółek.objects.all().filter(spolka_name=ver2, spolka_data__year='2019') # dane_2018_2 = Dane_spółek.objects.all().filter(spolka_name=ver2, spolka_data__year='2018') if (flaga20s == True): sum20201 = dane_2020_2.count() op2020v = dane_2020_2.aggregate(Sum('spolka_najwyzszy')) op22020v = dane_2020_2.aggregate(Sum('spolka_najnizszy')) ost1 = (op2020v['spolka_najwyzszy__sum'] - op22020v['spolka_najnizszy__sum']) / sum20201 else: ost1 = 0 if (flaga19s == True): sum12 = dane_2019_2.count() op12 = dane_2019_2.aggregate(Sum('spolka_najwyzszy')) op22 = dane_2019_2.aggregate(Sum('spolka_najnizszy')) ws = (op12['spolka_najwyzszy__sum'] - op22['spolka_najnizszy__sum']) / sum12 else: ws = 0 if (flaga18s == True): sum82 = dane_2018_2.count() op82 = dane_2018_2.aggregate(Sum('spolka_najwyzszy')) op821 = dane_2018_2.aggregate(Sum('spolka_najnizszy')) w8 = (op82['spolka_najwyzszy__sum'] - op821['spolka_najnizszy__sum']) / sum82 else: w8 = 0 # # k = 2020; # pusta_lista = [] # for i in range(10): # str(k) # dane_x = Dane_spółek.objects.all().filter(spolka_name=ver1, spolka_data__year=k) # k = int(k - 1); # sumx = dane_x.count() # opx = dane_x.aggregate(Sum('spolka_najwyzszy')) # op2x = dane_x.aggregate(Sum('spolka_najnizszy')) # ost = (opx['spolka_najwyzszy__sum'] - op2x['spolka_najnizszy__sum']) / sumx # pusta_lista.append(ost) # print(pusta_lista) k = 2020 pusta_lista = [] if (flaga20 and flaga19 and flaga18 == True): for i in range(10): str(k) if Dane_spółek.objects.filter( spolka_name=ver1, spolka_data__year=k).exists() == True: dane_x = Dane_spółek.objects.all().filter( spolka_name=ver1, spolka_data__year=k) k = int(k - 1) sumx = dane_x.count() opx = dane_x.aggregate(Sum('spolka_najwyzszy')) op2x = dane_x.aggregate(Sum('spolka_najnizszy')) ost = (opx['spolka_najwyzszy__sum'] - op2x['spolka_najnizszy__sum']) / sumx pusta_lista.append(ost) else: k = int(k - 1) ost = 0 pusta_lista.append(ost) else: for i in range(10): str(k) if Dane_spółek.objects.filter( spolka_name=ver1, spolka_data__year=k).exists() == True: dane_x = Dane_spółek.objects.all().filter( spolka_name=ver1, spolka_data__year=k) k = int(k - 1) sumx = dane_x.count() opx = dane_x.aggregate(Sum('spolka_najwyzszy')) op2x = dane_x.aggregate(Sum('spolka_najnizszy')) ost = (opx['spolka_najwyzszy__sum'] - op2x['spolka_najnizszy__sum']) / sumx pusta_lista.append(ost) else: k = int(k - 1) ost = 0 pusta_lista.append(ost) w = 2020 pusta_lista2 = [] # for i in range(10): # str(w) # dane_x = Dane_spółek.objects.all().filter(spolka_name=ver2, spolka_data__year=k) # w = int(w - 1); # sumx = dane_x.count() # opx = dane_x.aggregate(Sum('spolka_najwyzszy')) # op2x = dane_x.aggregate(Sum('spolka_najnizszy')) # ost = (opx['spolka_najwyzszy__sum'] - op2x['spolka_najnizszy__sum']) / sumx # pusta_lista2.append(ost) if (flaga20s and flaga19s and flaga18s == True): for i in range(10): str(w) if Dane_spółek.objects.filter( spolka_name=ver2, spolka_data__year=w).exists() == True: dane_x = Dane_spółek.objects.all().filter( spolka_name=ver2, spolka_data__year=w) w = int(w - 1) sumx = dane_x.count() opx = dane_x.aggregate(Sum('spolka_najwyzszy')) op2x = dane_x.aggregate(Sum('spolka_najnizszy')) ost = (opx['spolka_najwyzszy__sum'] - op2x['spolka_najnizszy__sum']) / sumx pusta_lista2.append(ost) else: w = int(w - 1) ost = 0 pusta_lista2.append(ost) else: for i in range(10): str(w) if Dane_spółek.objects.filter( spolka_name=ver2, spolka_data__year=w).exists() == True: dane_x = Dane_spółek.objects.all().filter( spolka_name=ver2, spolka_data__year=w) w = int(w - 1) sumx = dane_x.count() opx = dane_x.aggregate(Sum('spolka_najwyzszy')) op2x = dane_x.aggregate(Sum('spolka_najnizszy')) ost = (opx['spolka_najwyzszy__sum'] - op2x['spolka_najnizszy__sum']) / sumx pusta_lista2.append(ost) else: w = int(w - 1) ost = 0 pusta_lista2.append(ost) # sum2020 = dane_2020.count() # op2020 = dane_2020.aggregate(Sum('spolka_najwyzszy')) # op20202 = dane_2020.aggregate(Sum('spolka_najnizszy')) # ost = (op2020['spolka_najwyzszy__sum'] - op20202['spolka_najnizszy__sum']) / sum2020 # # sum1 = dane_2019.count() # op1 = dane_2019.aggregate(Sum('spolka_najwyzszy')) # op2 = dane_2019.aggregate(Sum('spolka_najnizszy')) # k = (op1['spolka_najwyzszy__sum'] - op2['spolka_najnizszy__sum']) / sum1 # print(k) # sum12 = dane_2019_2.count() # op12 = dane_2019_2.aggregate(Sum('spolka_najwyzszy')) # op22 = dane_2019_2.aggregate(Sum('spolka_najnizszy')) # w = (op12['spolka_najwyzszy__sum'] - op22['spolka_najnizszy__sum']) / sum12 # print(w) # sum8 = dane_2018.count() # op8 = dane_2018.aggregate(Sum('spolka_najwyzszy')) # op81 = dane_2018.aggregate(Sum('spolka_najnizszy')) # k8 = (op8['spolka_najwyzszy__sum'] - op81['spolka_najnizszy__sum']) / sum8 # print(k8) # # sum82 = dane_2018_2.count() # op82 = dane_2018_2.aggregate(Sum('spolka_najwyzszy')) # op821 = dane_2018_2.aggregate(Sum('spolka_najnizszy')) # w8 = (op82['spolka_najwyzszy__sum'] - op821['spolka_najnizszy__sum']) / sum82 # print(w8) print(kk) print(ws) print(k8) print(w8) print(ost) print(ost1) listaroczna = [] index = 2020 for i in range(10): listaroczna.append(index) index = 2020 - (i + 1) dane2 = { 'lista': listaroczna, 'dane_1': dane_1, 'dane_2': dane_2, 'nazwa_1': name1, 'nazwa_2': name2, 'Mx1': Mx1, 'Mx2': Mx2, 'My1': My1, 'My2': My2, 'Sx1': Sx1, 'Sx2': Sx2, 'Sy1': Sy1, 'Sy2': Sy2, 'dane_2020': dane_2020, 'dane_2019': dane_2019, 'dane_2018': dane_2018, 'dane_2020_2': dane_2020_2, 'dane_2019_2': dane_2019_2, 'dane_2018_2': dane_2018_2, 'zm': kk, 'zm2': ws, 'zm8': k8, 'zm28': w8, 'ww': ost, 'ww2': ost1, 'lis1': pusta_lista, 'lis2': pusta_lista2, 'dane_akt_1': dane_akt_1, 'dane_akt_2': dane_akt_2, } doc = DocxTemplate("Docx/my_word_template.docx") doc.render(dane2) doc.save("Docx/generated_doc_" + name1 + "_vs_" + name2 + "_report.docx") # dane = Dane_spółek.objects.all() return render(request, "Strona_3_ver2.html", dane2) else: return render(request, "Strona_2.html", context=context)
cliInn = generator(12) cliKpp = generator(9) cliIndex = generator(6) cliAddr = 'г. Москва, ул. Свободы, д. 15' cliName = 'ООО \"Невероятные приключения ДжоДжо\"' idNum = generator(8) osnDate = dategen('d') + ' ' + dategen('m') + ' ' + str(now.year) #billM = 77.46 #billI = 84.24 total = billM + billI tax = round(0.2 * total, 2) textstr = numToText(total) # In[43]: doc = DocxTemplate(inp) # заполняем шаблон нужными значениями context = { 'bankName': 'АО \"TikTok это круто\", Г. САНКТ-ПЕТЕРБУРГ', 'bicB': '133737133', 'accN': '13371337133713371337', 'inn1': '133713371337', 'kpp1': '133713371', 'billN': '1111101111000011', 'ourName': 'ООО \"Привет, Андрей\"', 'num': billNum, 'day': day, 'month': month, 'year34': year34, 'index1': '191111', 'address1': 'г. Санкт-Петербург, ул. Ломоносова, д. 9', 'clientName': cliName,
sd = tpl.new_subdoc(detectinfopath) sd.add_paragraph() if 'bigPannel' in catecode: sd = bigpannel_detect_info(sd) elif 'ycWcd' in catecode: sd = ycwcd_detect_info(sd) elif 'ycB' in catecode: sd = ycb_detect_info(sd) elif 'ycBplus' in catecode: sd = ycbplus_detect_info(sd) elif 'thys' in catecode: pass return else: sd = detect_info(sd, detectgene) sd.add_page_break() return sd if __name__ == '__main__': tplpath = os.path.join(basepath, 'blank.docx') detectinfo = detectinfo() for itemid in detectinfo: tpl = DocxTemplate(tplpath) context = summary(tpl, detectinfo[itemid]) word = os.path.join(basepath, 'detectinfo', itemid + '.docx') context = {'context': context} tpl.render(context, autoescape=True) tpl.save(word) print(f'检测信息更新成功')
def from_template(brand, model, fuel, price, template): template = DocxTemplate(template) context = get_context(brand, model, fuel, price) template.render(context) template.save(str(datetime.datetime.now().date()) + '_report.docx')
# -*- coding: utf-8 -*- from docxtpl import DocxTemplate from docxtpl import InlineImage from docx.shared import Inches import jinja2 doc = DocxTemplate("1_Смоленский б-р, дом 17, стр. 5 ТЗК _ФИНАЛ_ДЛЯ ТЗК.docx") images = {'main1.jpg': InlineImage(doc,'images/main1.jpg', width=Inches(4.73))} context = { 'customer': 'Фонд капитального ремонта многоквартирных домов города Москвы', 'adress': 'г. Москва, ЦАО, Смоленский б-р, дом 17, стр. 5', 'main_image': images['main1.jpg'], } jinja_env = jinja2.Environment(autoescape=True) doc.render(context, jinja_env) doc.save("result-final.docx")
def get_pubs_by_docx(request, type): if type == '5year': year_search = timezone.now().year - 5 promejutok = 'за последние 5 лет' elif type == 'allyear': year_search = 1920 promejutok = 'за все время' article_scopus = [] article_vak = [] article_rinc = [] patents = [] monograf = [] ucheb_posobie = [] def get_vol_in_pages(edition_info, authors): if re.search('статья в журнале - научная статья', edition_info['type']) or \ re.search('Article',edition_info['type']) or \ re.search('тезисы доклада на конференции', edition_info['type']) or\ re.search('статья в сборнике трудов конференции', edition_info['type']): pgs = str(edition_info['pages']).split("-") if len(pgs) > 1: raznost_pgs = int(pgs[1]) - int(pgs[0]) authors_cnt = len(authors.split(',')) res = "{0}/{1:.2f}".format(raznost_pgs, raznost_pgs / authors_cnt) else: res = "{0}/{1:.2f}".format(edition_info['pages'], 1 / len(authors.split(','))) else: pages_cnt = edition_info['pages'] if 'pages' in edition_info.keys( ) else 1 res = "{0}/{1:.2f}".format( pages_cnt, int(pages_cnt) / len(authors.split(','))) return res for item in Publications.objects.all(): if re.search(pytils.translit.translify(request.user.last_name), pytils.translit.translify(item.authors)): if item.year >= year_search: edition_info = eval(item.edition_info) #удаление автора из списка соавторов co_authors = str(item.authors).split(",") for it in co_authors: it.strip() if re.search(request.user.get_fullname(), it) or re.search( pytils.translit.translify(request.user.last_name), it): co_authors.remove(it) co_authors = ",".join(co_authors) if edition_info['type'] == 'патент на изобретение': patents.append({ 'id': len(patents) + 1, 'title': "{0} ({1})".format(item.title, edition_info['type']), 'biblio_info': "Номер патента: {0}. {1}г. {2}".format( edition_info['Номер патента'], item.year, edition_info['Страна']), 'vol_in_page': get_vol_in_pages(edition_info, item.authors), 'co_authors': co_authors, 'year': item.year }) elif edition_info['type'] == 'монография': monograf.append({ 'id': len(monograf) + 1, 'title': "{0} ({1})".format(item.title, edition_info['type']), 'biblio_info': "{0}. {1}. {2} с. ISBN:{3}".format( edition_info['edition'], item.year, edition_info['pages'], edition_info['isbn']), 'vol_in_page': get_vol_in_pages(edition_info, item.authors), 'co_authors': co_authors, 'year': item.year }) elif edition_info['type'] == 'учебное пособие': ucheb_posobie.append({ 'id': len(ucheb_posobie) + 1, 'title': "{0} ({1})".format(item.title, edition_info['type']), 'biblio_info': "{0}. {1}. {2} с. ISBN:{3}".format( edition_info['edition'], item.year, edition_info['pages'], edition_info['isbn']), 'vol_in_page': get_vol_in_pages(edition_info, item.authors), 'co_authors': co_authors, 'year': item.year }) elif re.search('статья в журнале - научная статья', str(edition_info['type'])) or re.search( 'Article', str(edition_info['type'])): if item.isScopusWoS: article_scopus.append({ 'id': len(article_scopus) + 1, 'title': "{0} ({1})".format(item.title, edition_info['type']), 'biblio_info': '// {0}. {1}. {2} №{3}. P.{4}.'.format( str(edition_info['name']).title(), item.year, 'V.' + edition_info['volume'] if edition_info['volume'] is not None else '', edition_info['number'], edition_info['pages']), 'vol_in_page': get_vol_in_pages(edition_info, item.authors), 'co_authors': co_authors, 'year': item.year }) else: format_rus = "//{0}. {1}. {2} №{3}. С.{4}." if edition_info[ 'lang'] == 'русский' else "//{0}. {1}. {2} №{3}. P.{4}." if 'volume' in edition_info.keys(): if edition_info[ 'volume'] is not None and edition_info[ 'volume']: if edition_info['lang'] == 'русский': vol = 'Т.{0}.'.format( edition_info['volume']) else: vol = 'V.{0}.'.format( edition_info['volume']) else: vol = '' article_vak.append({ 'id': len(article_vak) + 1, 'title': "{0} ({1})".format(item.title, edition_info['type']), 'biblio_info': format_rus.format( str(edition_info['name']).title(), item.year, vol, edition_info['number'], edition_info['pages']), 'vol_in_page': get_vol_in_pages(edition_info, item.authors), 'co_authors': co_authors, 'year': item.year }) elif re.search('тезисы доклада на конференции', str(edition_info['type'])) or re.search( 'статья в сборнике трудов конференции', str(edition_info['type'])): format_rus = "//{0}. {1}. С.{2}." if edition_info[ 'lang'] == 'русский' else "{0}. {1}. P.{2}." article_rinc.append({ 'id': len(article_rinc) + 1, 'title': "{0} ({1})".format(item.title, edition_info['type']), 'biblio_info': format_rus.format( str(edition_info['name']).title(), edition_info['conference'], edition_info['pages']), 'vol_in_page': get_vol_in_pages(edition_info, item.authors), 'co_authors': co_authors, 'year': item.year }) elif re.search('диссертация', str(edition_info['type'])): article_rinc.append({ 'id': len(article_rinc) + 1, 'title': "{0} ({1})".format(item.title, edition_info['type']), 'biblio_info': "// {0}. {1}. {2}c.".format( str(edition_info['type']).title(), item.year, edition_info['pages']), 'vol_in_page': get_vol_in_pages(edition_info, item.authors), 'co_authors': co_authors, 'year': item.year }) else: print('Пропущена публикация: ', edition_info['type'], ' ', item.authors, ' ', item.title, ' ', item.isScopusWoS) #расположение публикаций в хронологическом порядке article_scopus.sort(key=lambda a: a['year']) article_vak.sort(key=lambda a: a['year']) article_rinc.sort(key=lambda a: a['year']) ucheb_posobie.sort(key=lambda a: a['year']) monograf.sort(key=lambda a: a['year']) patents.sort(key=lambda a: a['year']) def set_ids(arr): id = 1 for item in arr: item['id'] = id id += 1 return arr article_scopus = set_ids(article_scopus) article_vak = set_ids(article_vak) article_rinc = set_ids(article_rinc) ucheb_posobie = set_ids(ucheb_posobie) patents = set_ids(patents) #формирование документа zaf_kav = generator_core.get_zaf_kaf(request.user.deparmt) rp_file_object = tempfile.NamedTemporaryFile( suffix='.docx') # create temp file document = DocxTemplate( os.path.join(os.path.join(settings.BASE_DIR, "static/doc_templ"), 'template_pubs.docx')) document.render( context={ 'author': { 'full_name': '{0} {1} {2}'.format(request.user.last_name, request.user. first_name, request.user.patronymic), 'IO_family': request.user.get_fullname() }, 'zav_kaf': { 'position': zaf_kav['position'], 'name': zaf_kav['name'] }, 'promejutok': promejutok, 'year': timezone.now().year, 'tbl_article_scopus': article_scopus, 'tbl_article_vak': article_vak, 'tbl_article_other': article_rinc, 'tbl_monografia': monograf, 'tbl_ucheb_posobiya_UMO': '', #-----------не сделано 'tbl_ucheb_posobiya': ucheb_posobie, 'tbl_ucheb_meth_izdanya': '', #-----------не сделано 'tbl_patents': patents, }) document.save(rp_file_object.name) res = HttpResponse( rp_file_object.file, content_type= 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) res['Content-Disposition'] = 'attachment; filename=result.docx' res['Content-Length'] = os.path.getsize(rp_file_object.name) return res
# -*- coding: utf-8 -*- ''' Created : 2015-03-12 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/order_tpl.docx') context = { 'customer_name' : 'Eric', '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) tpl.save('test_files/order.docx')
allele_frequency=None, mutation=None, interpretation="Enter interpretation here"): """ Returns a dict for use in the variant section of the template. Different from make_variant_table_entry! """ return { "gene": gene, "allele_frequency": allele_frequency, "mutation": mutation, "interpretation": interpretation } doc = DocxTemplate(sys.argv[1]) context = { 'nvariants': "999", 'variant_list': [ make_variant_list_entry(*args) for args in (('TEST1', 101, 'MUT1'), ('TEST2', 102, 'MUT2')) ], 'variant_tbl_entries': [ make_variant_table_entry(*args) for args in ( ('TEST1', 'TRANSCRIPT1', 'Hg19', 'chr1', '000000', '999999', 'G', 'A'), ('TEST2', 'TRANSCRIPT2', 'Hg19', 'chr2', '000000', '999999', 'C', 'G'), ) ],
def read_excel(): zpath = os.getcwd() + '/' try: filename = input('输入文件名: ') print(filename) my_file_name = zpath + filename my_file = Path(my_file_name) if my_file.exists(): pass else: print("文件不存在,重新输入文件名称!") os._exit() my_dir_name = zpath + filename.replace('.xls', '') my_dir = Path(my_dir_name) if my_dir.exists(): pass else: os.makedirs(my_dir) print("创建文件存储目录") # 打开excel x1 = xlrd.open_workbook(my_file_name) # 打开sheet1 table = x1.sheet_by_index(0) nrows = table.nrows print('生成报告数:' + str(nrows - 1)) for i in range(nrows - 1): number = table.cell_value(i + 1, 1) if number is None: break id = str(table.cell_value(i + 1, 2)).strip() name = str(table.cell_value(i + 1, 3)).strip() sex = str(table.cell_value(i + 1, 4)).strip() age = table.cell_value(i + 1, 5) tpl = DocxTemplate(zpath + 'person.docx') context = { 'number': number, 'id': id, 'name': name, 'sex': sex, } if age is None: context['age'] = '' else: if isinstance(age, float): context['age'] = int(float(age)) else: context['age'] = age temp = str(i + 1) saveFileName = my_dir_name + '/' + \ name.strip() + '_' + \ "_" + temp + '.docx' print(saveFileName) tpl.render(context) tpl.save(saveFileName) except Exception as err: print("err %s: " % err) blogpath = os.path.join(zpath, 'log_err.txt') f = open(blogpath, 'w+') f.writelines(repr(err)) f.close()
# get HV Nodes Info hvNodesFetcher = HvNodesInfoFetcher(appDbConStr) hvNodesInfoList: List[IHvNodesInfo] = hvNodesFetcher.fetchHvNodesInfo( startDate, endDate) reportContext['hvNodes'] = hvNodesInfoList # get LV Nodes Info lvNodesFetcher = LvNodesInfoFetcher(appDbConStr) lvNodesInfoList: List[ILvNodesInfo] = lvNodesFetcher.fetchLvNodesInfo( startDate, endDate) reportContext['lvNodes'] = lvNodesInfoList # generate report word file tmplPath = "assets/weekly_report_template.docx" doc = DocxTemplate(tmplPath) # # signature Image # signatureImgPath = 'assets/signature.png' # signImg = InlineImage(doc, signatureImgPath) # reportContext['signature'] = signImg doc.render(reportContext) dumpFileName = 'Weekly_no_{0}_{1}_to_{2}.docx'.format( weekNum, dt.datetime.strftime(startDate, '%d-%m-%Y'), dt.datetime.strftime(endDate, '%d-%m-%Y')) dumpFileFullPath = os.path.join(appConfig['dumpFolder'], dumpFileName) doc.save(dumpFileFullPath) print('Weekly report word file generation done...') # convert report to pdf
from docxtpl import DocxTemplate doc = DocxTemplate("files/my_word_template.docx") context = {'company_name': "World company"} doc.render(context) doc.save("files/generated_doc.docx") # http://docxtpl.readthedocs.io/en/latest/
from docxtpl import DocxTemplate, InlineImage, RichText from docx.shared import Mm, Inches, Pt import jinja2 tpl = DocxTemplate('fujian03.docx') rt_hukou = RichText('') rt_hukou.add('内蒙古突泉县', size=12) # 字体大小 rt_id_number = RichText('') rt_id_number.add('内蒙古突泉县', size=12) # 字体大小 rt_p_status = RichText('') rt_p_status.add('共青团员', size=12) # 字体大小 id_number = '152224199101104567' context = { 'r_e': '韩小顺', 'sa': '男', 'bir': '1991-01-10', 'edu': '本科', 'id_number': '15222419910110651x', 'work_unit': '青峰白羽软件技术工作室', 'f_p': '021-09765432', 'u_n': '私营企业', 'profession': '计算机软件', 's_w_d': '2015-08-20', 'cl': '4', 'hukou': rt_hukou, 'address': '北京大兴区旧宫镇', 'unit_address': '北京大兴区旧宫镇', 'email': '北京大兴区旧宫镇',
def readFlies(self, tplName): ''' 文件读取函数 ''' tpl = DocxTemplate(tplName) return tpl
def render_document(template, filename, data): print(data) doc = DocxTemplate(template) context = data # Possibly do some sanitizing doc.render(context) doc.save(filename)
# -*- coding: utf-8 -*- import docx from docxtpl import DocxTemplate from constructor.templates.co.forms import PersonForm basedock = DocxTemplate("/Users/liliatagirova/Desktop/Доки/basedock.docx") var3 = DocxTemplate("/Users/liliatagirova/Desktop/Доки/variable3.docx") var5 = DocxTemplate("/Users/liliatagirova/Desktop/Доки/variable5.docx") var7 = DocxTemplate("/Users/liliatagirova/Desktop/Доки/variable7.docx") final_dock = DocxTemplate("final.docx") name = PersonForm.first_name print(name) context = { 'name' : name, 'last_name': " 11", 'fam_name': "22"} ''' doc1 = docx.Document('example.docx') doc2 = docx.Document('restyled.docx') # получаем из первого документа стили всех абзацев styles = [] for paragraph in doc1.paragraphs: styles.append(paragraph.style) # применяем стили ко всем абзацам второго документа for i in range(len(doc2.paragraphs)): doc2.paragraphs[i].style = styles[i] doc2.save('restored.docx') ''' text = [] for paragraph in var5.paragraphs:
def generate_document(template, context, filename): """Generate word document from template""" doc = DocxTemplate(template) doc.render(context=context) doc.save(filename)
def create_source_docx_partner(self, cr, uid, ids, report, records, init_pay, context=None): # 2016-11-2 支持了图片 # 1.导入依赖,python3语法 # from . import report_helper # 2. 需要添加一个"tpl"属性获得模版对象 tempname = tempfile.mkdtemp() temp_out_file = self.generate_temp_file(tempname) doc = DocxTemplate(misc.file_open(report.template_file).name) env = api.Environment(cr, uid, context) partner = env.get('partner').search([('id', '=', context.get('partner_id'))]) simple_dict = {'partner_name': partner.name, 'from_date': context.get('from_date'), 'to_date': context.get('to_date'), 'report_line': [], 'init_pay': {}, 'final_pay': {}} if not records: if init_pay: simple_dict['init_pay'] = init_pay simple_dict['final_pay'] = init_pay doc.render({'obj': simple_dict, 'tpl': doc}, report_helper.get_env()) doc.save(temp_out_file) report_stream = '' with open(temp_out_file, 'rb') as input_stream: report_stream = input_stream.read() os.remove(temp_out_file) return report_stream, report.output_type data = DataModelProxy(records) for p_value in data: simple_dict['report_line'].append({ 'date': p_value.date, 'name': p_value.name, 'note': p_value.note, 'amount': p_value.amount, 'pay_amount': p_value.pay_amount, 'discount_money': p_value.discount_money, 'balance_amount': p_value.balance_amount }) if data: simple_dict['init_pay'] = data[0].balance_amount - data[0].amount + data[0].pay_amount - data[ 0].discount_money simple_dict['final_pay'] = data[-1].balance_amount doc.render({'obj': simple_dict, '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
# -*- coding: utf-8 -*- ''' Created : 2015-03-12 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/header_footer_entities_tpl.docx') context = { 'title' : 'Header and footer test', } tpl.render(context) tpl.save('test_files/header_footer_entities.docx')
class doc(object): def __init__(self): base_url = getDir() + '/user/user_template/' #初始化生成一个doc对象 asset_url = base_url + 'demo.docx' self.tpl = DocxTemplate(asset_url) self.webvul = self.tpl.new_subdoc() #web应用漏洞 self.appvul = self.tpl.new_subdoc() #应用程序漏洞 self.devicevul = self.tpl.new_subdoc() #网络设备漏洞 self.sysvul = self.tpl.new_subdoc() #操作系统应用漏洞 self.time = self.tpl.new_subdoc() self.number = 0 def add_title(self, title, type , level=3): doc = self.check_type(type) run = doc.add_heading('', level=level).add_run(title) run.font.name = "宋体" run.font.size = Pt(14) r = run.element r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') def add_table(self,jsons, type=1): ''' 在doc中添加表格 :param json: type:1为web漏洞2为应用程序漏洞,3为网络设备漏洞4为系统漏洞 :return: ''' #获取要写入的subdoc节点 doc = self.check_type(type) for json in jsons: # j控制json字典下标 #print(json) j = 0 title = json['title'] #生成标题 self.number += 1 self.add_title(title,type=type) table = doc.add_table(rows=len(json)-1, cols=2, style="Style1")#新建一个表格 table.autofit = False for key, value in json.items(): if j == 0: j +=1 else: table.columns[0].width = Cm(3) table.columns[1].width = Cm(12) table.cell(j - 1, 0).width = Cm(3) #设置单元格宽度 table.cell(j - 1, 1).width = Cm(12) #table.alignment=WD_TABLE_ALIGNMENT.RIGHT 设置对齐方式 keyCell = table.cell(j-1, 0) #表格赋值 valueCell = table.cell(j-1, 1) #设置key单元格字体与字体大小 key_paragraph = keyCell.paragraphs[0] #keyRun = keyCell.paragraphs[0].add_run(key) keyRun = key_paragraph.add_run(key) keyRun.font.name = u'微软雅黑' # 设置字体 keyRun._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') keyRun.font.size = Pt(10.5) # 设置字号为五号 key_paragraph.paragraph_format.line_spacing = WD_LINE_SPACING.ONE_POINT_FIVE#设置1.5倍行间距 key_paragraph.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT #设置水平对齐方式右对齐 keyCell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER #设置value单元格字体与字体大小 val_paragraph = valueCell.paragraphs[0] #valueRun = valueCell.paragraphs[0].add_run(value) # 填入的内容 valueRun = val_paragraph.add_run(value) valueRun.font.name = u'微软雅黑' # 设置字体 valueRun.font.size = Pt(10.5) # 设置字号为五号 valueRun._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') val_paragraph.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE#设置1.5倍行间距 val_paragraph.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT#设置水平对齐方式左对齐 valueCell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER #keyCell.text = key #valueCell.text = value #print(key,value) j = j+1 #赋值给初始话的subdoc值 if type==1: self.webvul=doc elif type==2: self.appvul= doc elif type==3: self.devicevul = doc else: self.sysvul = doc #保存docx文档 def save_doc(self,current_time, start_time): #添加doc编辑时间 filename = "上海驭胜信息安全通告(%s至%s).docx" % (str(start_time),str(current_time)) content = {'subdoc': self.webvul, 'appdoc':self.appvul, 'devicedoc': self.devicevul, 'sysdoc': self.sysvul, 'time': current_time , 'start_time': start_time, 'end_time': current_time} self.tpl.render(content) self.tpl.save(filename) print("file %s success to save!" % filename) def check_type(self,num): if num==1: return self.webvul elif num ==2: return self.appvul elif num ==3: return self.devicevul else: return self.sysvul def add_hyperlink(self,paragraph, text, url): # This gets access to the document.xml.rels file and gets a new relation id value part = paragraph.part r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True) # Create the w:hyperlink tag and add needed values hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink') hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, ) # Create a w:r element and a new w:rPr element new_run = docx.oxml.shared.OxmlElement('w:r') rPr = docx.oxml.shared.OxmlElement('w:rPr') # Join all the xml elements together add add the required text to the w:r element new_run.append(rPr) new_run.text = text hyperlink.append(new_run) # Create a new Run object and add the hyperlink into it r = paragraph.add_run () r.font.name = u'微软雅黑' # 设置字体 r.font.size = Pt(10.5) # 设置字号为五号 r._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') r._r.append (hyperlink) # A workaround for the lack of a hyperlink style (doesn't go purple after using the link) # Delete this if using a template that has the hyperlink style in it r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK r.font.underline = True return hyperlink
def export_resume(self,ids): # 定义压缩文件流 zip_stream = StringIO() resume_zip = zipfile.ZipFile(zip_stream,'w') # 将参数转为列表 id_list = json.loads(ids) # 获取要到处简历的员工 Model = request.session.model('hr.employee') employees = Model.search_read([('id','in',id_list)]) job='' for i,employee in enumerate(employees): # 获取模板 path = os.path.abspath(os.path.dirname(sys.argv[0])) tpl = DocxTemplate(path.replace('\\','/')+'/myaddons/nantian_erp/resume_template.docx') # 简历写入的文件流 fp = StringIO() experiences_list = [] certifications_dict=[] if employee['job_id']: job = employee['job_id'][1] if employee['work_experience_ids']: Model = request.session.model('nantian_erp.work_experience') experiences = Model.search_read([('id','in',employee['work_experience_ids'])]) for exper in experiences: exper_dict = {'date':exper['date'] or '','name':exper['name'].replace('&','&') or '','job':exper['job'].replace('&','&') or '','description':exper['description'].replace('&','&') or ''} experiences_list.append(exper_dict) if employee['certificate_ids']: count = 0 Model = request.session.model('nantian_erp.certificate') certificates = Model.search_read([('id','in',employee['certificate_ids'])]) for cer in certificates: count = count + 1 image = '' name = '' if cer['image']: # 将base64 转为图片 f = StringIO(base64.b64decode(str(cer['image']))) print "查看图片名称%d"%count try: image = InlineImage(tpl,f) except Exception: pass #image = InlineImage(tpl,f,height=Mm(30)) f.close() if cer['name']: name = cer['name'].replace('&','&') certificate = {'name':name or '','image': image or '',} certifications_dict.append(certificate) gender = '' if employee['gender'] == 'male': gender = u'男' elif employee['gender'] == 'female': gender = u'女' # 模板所需数据 resume_dict = {'name':employee['name'] or '', 'gender':gender or '', 'birthday':employee['birthday']or '', 'education':employee['education']or '', 'graduction':employee['graduation']or '', 'major':employee['major']or '', 'job':job or '', 'work_time':employee['work_time']or '', 'specialty':employee['specialty']or '', 'work_experiences':experiences_list or [], 'certifications':certifications_dict or [], } # encode_json = json.dumps(resume_dict) # rep_resume_dict = encode_json.replace('&','&') # resume_dict = json.loads(rep_resume_dict) # print resume_dict tpl.render(resume_dict) tpl.save(fp) fp.seek(0) resume_zip.writestr(employee['name']+u'简历'+'.docx',fp.getvalue()) fp.close() resume_zip.close() zip_stream.seek(0) # 返回压缩文件 return request.make_response(zip_stream.getvalue() , headers=[('Content-Disposition',content_disposition(u'简历'+'.zip')), ('Content-Type', 'application/zip')], )
良好的散热不仅降低了系统热设计成本,同时提升了系统在高温环境的可靠性。' MyContent_secondP = 'PXFC211507SC可广泛应用于2110MHz-2170MHz频段的功率放大器中,具有20.4dB的增益,\ 无需外围匹配电路即可实现宽带的输入输出匹配。其基板面积仅为26.3mm × 9.78mm(见图3),可减小PCB板的面积,易于实现产品的小型化。' MyContent_thirdP = '2170MHz,28V下,PXFC211507SC的单载波WCDMA性能如下,输出功率为32W,增益可达20dB,效率为32%。' arr1 = [] arr1.append('宽带内输入输出匹配') arr1.append('2170MHz,28V下,其CW性能如下,P1dB输出功率为150W,增益可达19dB,效率高达56%') arr1.append('2170MHz,28V下,其单载波WCDMA性能如下,输出功率为32W,增益可达20dB,效率32%') arr2 = [] arr2.append('移动通信设备') arr2.append('多标准蜂窝功率放大器') arr2.append('蜂窝基础设施') doc = DocxTemplate("templet.docx") context = { 'MyTable' : [ {'title' : MyContent_title, 'type' : MyContent_type, 'factory' : MyContent_factory, 'version' : MyContent_version, 'abstract' : MyContent_abstract, 'key' : MyContent_key, 'app' : MyContent_app, 'category' : MyContent_category, 'ref' : MyContent_ref, 'author' : MyContent_author } ], 'MyFirstP' : MyContent_firstP , 'MySecondP' : MyContent_secondP , 'MyThirdP' : MyContent_thirdP } doc.render(context) doc.save("generated_temp.docx")
# -*- coding: utf-8 -*- ''' Created : 2015-03-12 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate, RichText tpl=DocxTemplate('test_files/cellbg_tpl.docx') context = { 'alerts' : [ {'date' : '2015-03-10', 'desc' : RichText('Very critical alert',color='FF0000', bold=True), 'type' : 'CRITICAL', 'bg': 'FF0000' }, {'date' : '2015-03-11', 'desc' : RichText('Just a warning'), 'type' : 'WARNING', 'bg': 'FFDD00' }, {'date' : '2015-03-12', 'desc' : RichText('Information'), 'type' : 'INFO', 'bg': '8888FF' }, {'date' : '2015-03-13', 'desc' : RichText('Debug trace'), 'type' : 'DEBUG', 'bg': 'FF00FF' }, ], } tpl.render(context) tpl.save('test_files/cellbg.docx')
machnt_risk_form = round(machnt_risk, 2) context = machnt_risk_form.to_dict(orient='records') #context = machnt_risk.set_index('mchnt_cd').T.to_dict('list') table = {'tbl_contents': context} ''' table = { 'user_labels': ['fruit', 'vegetable', 'stone', 'thing'], 'tbl_contents': [ {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']}, {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']}, {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']}, ], } ''' tpl = DocxTemplate( r'C:/工作/典型事件/手机POS交易数据疑似套现/拉卡拉商户交易明细/商户交易日监测报告/商户交易日监测报告_tpl.docx') rt_date = RichText() rt_date.add(time_str + '\n', font='方正小标宋简体', size=44) rt_pargh1 = RichText() rt_pargh1.add( time_str + '新增商户' + str(mchnt_curr_day) + '家,新增交易笔数' + str(trans_num_curr_day) + '笔,新增交易金额' + str(round(trans_at_curr_day, 2)) + '元,贷记卡交易金额占比为' + format(trans_at_loan_curr_day, '.2%') + '。本日活跃商户数为:' + str(mchnt_day_live) + ',本周活跃商户数为:' + str(mchnt_week_live) + ',本月活跃商户数为:' + str(mchnt_month_live) + ',本日交易金额为过去30天均值的' + str(round(trans_at_30_ratio, 2)) + '倍' + ',交易笔数为过去30天均值的' + str(round(trans_num_30_ratio, 2)) + '倍' + ',贷记卡交易金额为过去30天均值的' + str(round(loan_trans_at_30_ratio, 2)) + '倍' + ',贷记卡交易笔数为过去30天均值的' + str(round(loan_trans_num_30_ratio, 2)) + '倍' + ',5000元以上贷记卡交易金额为过去30天均值的' + str(round(loan_trans_5000_at_30_day_ratio, 2)) + '倍' + ',5000元以上贷记卡交易笔数为过去30天均值的' +
# -*- coding: utf-8 -*- """ Created on Fri May 22 15:21:58 2020 @author: Lenovo """ from django.shortcuts import render from docxtpl import DocxTemplate,InlineImage from docx.shared import Mm, Inches, Pt base_url = 'E:/GZ/Django/Django_API-1/Django_baogao/DjangoWord/Python_docx/' asset_url = base_url + 'test模板.docx' tpl = DocxTemplate(asset_url) #所有需要插入的数据只能在一个{}里面 context = {'text': '哈哈哈,来啦', 't1':'燕子', 't2':'杨柳', 't3':'桃花', 't4':'针尖', 't5':'头涔涔', 't6':'泪潸潸', 't7':'茫茫然', 't8':'伶伶俐俐', 'picture1': InlineImage(tpl, '1.jpg', width=Mm(80), height=Mm(60)),} user_labels = ['姓名', '年龄', '性别', '入学日期'] context['user_labels'] = user_labels user_dict1 = {'number': 1, 'cols': ['林小熊', '27', '男', '2019-03-28']}
def generate_electrical_docx(project_chapter6_type, args): # ********************************************** print("*" * 30) # step:1 # 载入参数 print("---------step:1 载入参数--------") # chapter 6 Dict_6 = {} # project_chapter6_type = ['山地'] # args=[19, 22, 8, 1.5, 40, 6] project01 = WireRod(project_chapter6_type, *args) project01.aluminium_cable_steel_reinforced("LGJ_240_30") args_chapter6_01_name = ['钢芯铝绞线'] args_chapter6_01_type = ['LGJ_240_30'] for i in range(0, len(args_chapter6_01_name)): if args_chapter6_01_name[i] == '钢芯铝绞线': print("---------线材:钢芯铝绞线--------") key_dict = args_chapter6_01_type[i] if key_dict == 'LGJ_240_30': value_dict = str( project01.aluminium_cable_steel_reinforced_length_weight) Dict_6[key_dict] = value_dict print("---------线材生成完毕--------") electrical_insulator_name_list = ['复合绝缘子', '瓷绝缘子', '复合针式绝缘子', '复合外套氧化锌避雷器'] electrical_insulator_type_list = [ 'FXBW4_35_70', 'U70BP_146D', 'FPQ_35_4T16', 'YH5WZ_51_134' ] tower_type_list = [ '单回耐张塔', '单回耐张塔', '单回耐张塔', '单回直线塔', '单回直线塔', '双回耐张塔', '双回耐张塔', '双回直线塔', '双回直线塔', '铁塔电缆支架' ] tower_type_high_list = [ 'J2_24', 'J4_24', 'FS_18', 'Z2_30', 'ZK_42', 'SJ2_24', 'SJ4_24', 'SZ2_30', 'SZK_42', '角钢' ] tower_weight_list = [ 6.8, 8.5, 7, 5.5, 8.5, 12.5, 17, 6.5, 10, 0.5, ] tower_height_list = [32, 32, 27, 37, 49, 37, 37, 42, 54, 0] tower_foot_distance_list = [5.5, 5.5, 6, 5, 6, 7, 8, 6, 8, 0] project_chapter6_type = ['山地'] project02 = ElectricalInsulator(project_chapter6_type, *args) project02.sum_cal_tower_type(tower_type_list, tower_type_high_list, tower_weight_list, tower_height_list, tower_foot_distance_list) project02.electrical_insulator_model(project_chapter6_type, electrical_insulator_name_list, electrical_insulator_type_list) args_chapter6_02_type = electrical_insulator_type_list for i in range(0, len(args_chapter6_02_type)): key_dict = args_chapter6_02_type[i] if key_dict == 'FXBW4_35_70': value_dict = str(project02.used_numbers_FXBW4_35_70) Dict_6[key_dict] = value_dict if key_dict == 'U70BP_146D': value_dict = str(project02.used_numbers_U70BP_146D) Dict_6[key_dict] = value_dict if key_dict == 'FPQ_35_4T16': value_dict = str(project02.used_numbers_FPQ_35_4T16) Dict_6[key_dict] = value_dict if key_dict == 'YH5WZ_51_134': value_dict = str(project02.used_numbers_YH5WZ_51_134) Dict_6[key_dict] = value_dict print("---------绝缘子生成完毕--------") args_chapter6_03_type = tower_type_high_list project03 = TowerType(project_chapter6_type, *args) project03.sum_cal_tower_type(tower_type_list, tower_type_high_list, tower_weight_list, tower_height_list, tower_foot_distance_list) for i in range(0, len(args_chapter6_03_type)): key_dict = args_chapter6_03_type[i] if key_dict == 'J2_24': value_dict = str(project03.used_numbers_single_J2_24) Dict_6[key_dict] = value_dict if key_dict == 'J4_24': value_dict = str(project03.used_numbers_single_J4_24) Dict_6[key_dict] = value_dict if key_dict == 'FS_18': value_dict = str(project03.used_numbers_single_FS_18) Dict_6[key_dict] = value_dict if key_dict == 'Z2_30': value_dict = str(project03.used_numbers_single_Z2_30) Dict_6[key_dict] = value_dict if key_dict == 'ZK_42': value_dict = str(project03.used_numbers_single_ZK_42) Dict_6[key_dict] = value_dict if key_dict == 'SJ2_24': value_dict = str(project03.used_numbers_double_SJ2_24) Dict_6[key_dict] = value_dict if key_dict == 'SJ4_24': value_dict = str(project03.used_numbers_double_SJ4_24) Dict_6[key_dict] = value_dict if key_dict == 'SZ2_30': value_dict = str(project03.used_numbers_double_SZ2_30) Dict_6[key_dict] = value_dict if key_dict == 'SZK_42': value_dict = str(project03.used_numbers_double_SZK_42) Dict_6[key_dict] = value_dict if key_dict == '角钢': value_dict = str(project03.used_numbers_angle_steel) Dict_6[key_dict] = value_dict Dict_6['铁塔合计'] = str(project03.sum_used_numbers) print("---------铁塔生成完毕--------") tower_base_list = ['ZJC1', 'ZJC2', 'JJC1', 'JJC2', 'TW1', 'TW2', '基础垫层'] c25_unit_list = [12, 16, 42, 80, 8.8, 10.2, 2.4] steel_unit_list = [300, 500, 750, 900, 600, 800, 0] foot_bolt_list = [100, 180, 280, 360, 100, 180, 0] args_chapter6_04_type = tower_base_list project04 = TowerBase(project_chapter6_type, *args) project04.sum_cal_tower_type(tower_type_list, tower_type_high_list, tower_weight_list, tower_height_list, tower_foot_distance_list) project04.sum_cal_tower_base(tower_base_list, c25_unit_list, steel_unit_list, foot_bolt_list) for i in range(0, len(args_chapter6_04_type)): key_dict = args_chapter6_04_type[i] if key_dict == 'ZJC1': Dict_6['ZJC1_num'] = str(project04.used_numbers_base_zjc1) Dict_6['c25_sum_zjc1'] = str(project04.c25_sum_zjc1) Dict_6['steel_sum_zjc1'] = str(project04.steel_sum_zjc1) if key_dict == 'ZJC2': Dict_6['ZJC2_num'] = str(project04.used_numbers_base_zjc2) Dict_6['c25_sum_zjc2'] = str(project04.c25_sum_zjc2) Dict_6['steel_sum_zjc2'] = str(project04.steel_sum_zjc2) if key_dict == 'JJC1': Dict_6['JJC1_num'] = str(project04.used_numbers_base_jjc1) Dict_6['c25_sum_jjc1'] = str(project04.c25_sum_jjc1) Dict_6['steel_sum_jjc1'] = str(project04.steel_sum_jjc1) if key_dict == 'JJC2': Dict_6['jjc2_num'] = str(project04.used_numbers_base_jjc2) Dict_6['c25_sum_jjc2'] = str(project04.c25_sum_jjc2) Dict_6['steel_sum_jjc2'] = str(project04.steel_sum_jjc2) if key_dict == 'TW1': Dict_6['tw1_num'] = str(project04.used_numbers_base_tw1) Dict_6['c25_sum_tw1'] = str(project04.c25_sum_tw1) Dict_6['steel_sum_tw1'] = str(project04.steel_sum_tw1) if key_dict == 'TW2': Dict_6['tw2_num'] = str(project04.used_numbers_base_tw2) Dict_6['c25_sum_tw2'] = str(project04.c25_sum_tw2) Dict_6['steel_sum_tw2'] = str(project04.steel_sum_tw2) if key_dict == '基础垫层': Dict_6['base_layer'] = str(project04.used_numbers_base_layer) Dict_6['c25_sum_layer'] = str(project04.c25_sum_layer) Dict_6['steel_sum_layer'] = str(project04.steel_sum_layer) Dict_6['基础数量合计'] = str(project04.used_numbers_base_sum) Dict_6['基础混凝土合计'] = str(project04.c25_sum) Dict_6['基础钢筋合计'] = str(project04.steel_sum) print("---------铁塔基础生成完毕--------") cable_project_list = ['高压电缆', '高压电缆', '电缆沟', '电缆终端', '电缆终端'] cable_model_list = [ 'YJLV22_26_35_3_95_gaoya', 'YJV22_26_35_1_300_gaoya', '电缆沟长度', 'YJLV22_26_35_3_95_dianlanzhongduan', 'YJV22_26_35_1_300_dianlanzhongduan' ] args_chapter6_05_type = cable_model_list project05 = Cable(project_chapter6_type, *args) project05.sum_cal_cable(cable_project_list, cable_model_list) for i in range(0, len(args_chapter6_05_type)): key_dict = args_chapter6_05_type[i] if key_dict == 'YJLV22_26_35_3_95_gaoya': Dict_6['YJLV22_26_35_3_95_gaoya'] = str( project05.cable_model_YJLV22_26_35_3_95_gaoya) if key_dict == 'YJV22_26_35_1_300_gaoya': Dict_6['YJV22_26_35_1_300_gaoya'] = str( project05.cable_model_YJV22_26_35_1_300_gaoya) if key_dict == '电缆沟长度': Dict_6['电缆沟长度'] = str(project05.cable_model_cable_duct) if key_dict == 'YJLV22_26_35_3_95_dianlanzhongduan': Dict_6['YJLV22_26_35_3_95_dianlanzhongduan'] = str( project05.cable_model_YJLV22_26_35_3_95_dianlanzhongduan) if key_dict == 'YJV22_26_35_1_300_dianlanzhongduan': Dict_6['YJV22_26_35_1_300_dianlanzhongduan'] = str( project05.cable_model_YJV22_26_35_1_300_dianlanzhongduan) # print(Dict_6) path_images = r"C:\Users\Administrator\PycharmProjects\docx_project\files\results" tpl = DocxTemplate( r'C:\Users\Administrator\PycharmProjects\Odoo_addons_NB\autocrword\models\chapter_6\CR_chapter6_template.docx' ) tpl.render(Dict_6) tpl.save( r'C:\Users\Administrator\PycharmProjects\Odoo_addons_NB\autocrword\models\chapter_6\result_chapter6_e.docx' ) print("---------chapter 6 生成完毕--------")
# -*- coding: utf-8 -*- ''' Created : 2017-09-03 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate DEST_FILE = 'test_files/header_footer_image.docx' tpl=DocxTemplate('test_files/header_footer_image_tpl.docx') context = { 'mycompany' : 'The World Wide company', } tpl.replace_media('test_files/dummy_pic_for_header.png','test_files/python.png') tpl.render(context) tpl.save(DEST_FILE)
def fill_jinja(input_file, output_file, context): doc = DocxTemplate(input_file) # context = find_context() doc.render(context) doc.save(output_file)
# -*- coding: utf-8 -*- ''' Created : 2016-07-19 @author: AhnSeongHyun Edited : 2016-07-19 by Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/header_footer_tpl_utf8.docx') sd = tpl.new_subdoc() p = sd.add_paragraph(u'This is a sub-document to check it does not break header and footer with utf-8 characters inside the template .docx') context = { 'title' : u'헤더와 푸터', 'company_name' : u'세계적 회사', 'date' : u'2016-03-17', 'mysubdoc' : sd, } tpl.render(context) tpl.save('test_files/header_footer_utf8.docx')
# -*- coding: utf-8 -*- ''' Created : 2015-03-26 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate, RichText tpl = DocxTemplate('test_files/richtext_tpl.docx') rt = RichText('an exemple of ') rt.add('a rich text', style='myrichtextstyle') rt.add(' with ') rt.add('some italic', italic=True) rt.add(' and ') rt.add('some violet', color='#ff00ff') rt.add(' and ') rt.add('some striked', strike=True) rt.add(' and ') rt.add('some small', size=14) rt.add(' or ') rt.add('big', size=60) rt.add(' text.') rt.add(' Et voilà ! ') rt.add('\n1st line') rt.add('\n2nd line') rt.add('\n3rd line') rt.add('\n\n<cool>') rt.add('\nFonts :\n', underline=True) rt.add('Arial\n', font='Arial')
from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/dynamic_table_tpl.docx') context = { 'col_labels' : ['fruit', 'vegetable', 'stone', 'thing'], 'tbl_contents': [ {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']}, {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']}, {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']}, ] } tpl.render(context) tpl.save('test_files/dynamic_table.docx')
from docxtpl import DocxTemplate from datetime import datetime from num2t4ru import num2text import math expansion = 'docx' filename = "template" input_file = f"{filename}.{expansion}" doc = DocxTemplate(input_file) nds = 20 sum = 315100.80 round_sum = '{0:,}'.format(int(sum)).replace(',', ' ') sum_kop = (math.floor(sum * 100) % 100) if sum_kop == 0: sum_kop = str(sum_kop) + '0' sum_nds = round(sum * nds / 100 / (1 + nds / 100), 2) sum_nds_kop = (math.floor(sum_nds * 100) % 100) if sum_nds_kop == 0: sum_nds_kop = str(sum_nds_kop) + '0' male_units = ((u'рубль', u'рубля', u'рублей'), 'm') female_units = ((u'копейка', u'копейки', u'копеек'), 'f') context = { 'ikz': "212621500152762150100100480000000244", 'work': "электромонтажные и сантехнические работы на 4-ом этаже главного учебного корпуса", 'work_name': "Электромонтажные и сантехнические работы на 4-ом этаже главного учебного корпуса", 'company_work': "Общество с ограниченной ответственностью «СпецЭлектроМонтаж»", 'company_work_schief': "генерального директора Варина Дмитрия Васильевича", 'na_osnovanii': "Устава", 'company_work_schief_sm': "Д.В. Варин",
# -*- coding: utf-8 -*- ''' Created : 2015-03-12 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate from docx.shared import Inches tpl=DocxTemplate('test_files/subdoc_tpl.docx') sd = tpl.new_subdoc() p = sd.add_paragraph('This is a sub-document inserted into a bigger one') p = sd.add_paragraph('It has been ') p.add_run('dynamically').style = 'dynamic' p.add_run(' generated with python by using ') p.add_run('python-docx').italic = True p.add_run(' library') sd.add_heading('Heading, level 1', level=1) sd.add_paragraph('This is an Intense quote', style='IntenseQuote') sd.add_paragraph('A picture :') sd.add_picture('python_logo.png', width=Inches(1.25)) sd.add_paragraph('A Table :') table = sd.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id'
def CreateWord(gender, group, surname, name, lastname, number, typeconcession, chooseDoc): # Проверка на пустоту if gender is None or group is None or surname is None or name is None or lastname is None or number is None or typeconcession is None: return "Error NoData" # Проверка наличия данных if gender == '' or group == '' or surname == '' or name == '' or lastname == '' or number == '' or typeconcession == '': return "Error NoData" # Проверка длинны полученных данных, ограничение 128 символов if len(group) > 128 or len(group) > 128 or len(group) > 128 or len( group) > 128 or len(group) > 128 or len(group) > 128: return "Error Len" # Проверка полученного пола, и перевод его в текст if gender != "1" and gender != "0": return "Error Gender" gender = GenderMass[int(gender)] # Задание параметров для шаблона и сохранение результата random.seed() if chooseDoc == '1': doc = DocxTemplate("template1.docx") elif chooseDoc == '2': doc = DocxTemplate("template2.docx") #doc = DocxTemplate("BlankMatHelp.docx") typeconcession = 10 else: print("chooseDoc error") return "Error no chooseDoc" if int(typeconcession) < 0 or int(typeconcession) > 10: return "Error typeConcession" typeconcession = ConcessionMass[int(typeconcession)] director = chooseDirector(group) context = { 'gender': gender, 'group': group, 'surname': surname, 'name': name, 'lastname': lastname, 'number': number, 'typeconcession': typeconcession, 'director': director } doc.render(context) LogFile = True File_Path = "" while LogFile: try: File_Path = "temp" + str(random.randint(1, 10000)) + ".docx" file = open(File_Path) file.close() except IOError as e: break # Формирование ответа для пользователя doc.save(File_Path) File_Path = os.path.abspath(File_Path) fp = open(File_Path, "rb") response = HttpResponse(fp.read()) fp.close() file_type = mimetypes.guess_type(File_Path) if file_type is None: file_type = 'application/octet-stream' response['Content-Type'] = file_type response['Content-Length'] = str(os.stat(File_Path).st_size) response[ 'Content-Disposition'] = "attachment; filename=Zaiavlenui_Na_matpomosh.docx" # Чистка временнойго файла os.remove(File_Path) return response
# -*- coding: utf-8 -*- ''' Created : 2016-03-26 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('templates/nested_for_tpl.docx') context = { 'dishes' : [ {'name' : 'Pizza', 'ingredients' : ['bread','tomato', 'ham', 'cheese']}, {'name' : 'Hamburger', 'ingredients' : ['bread','chopped steak', 'cheese', 'sauce']}, {'name' : 'Apple pie', 'ingredients' : ['flour','apples', 'suggar', 'quince jelly']}, ], 'authors' : [ {'name' : 'Saint-Exupery', 'books' : [ {'title' : 'Le petit prince'}, {'title' : "L'aviateur"}, {'title' : 'Vol de nuit'}, ]}, {'name' : 'Barjavel', 'books' : [ {'title' : 'Ravage'}, {'title' : "La nuit des temps"}, {'title' : 'Le grand secret'}, ]}, ] }
from docxtpl import DocxTemplate doc = DocxTemplate('info.docx') p = doc.tables[0].rows[0].cells[0].add_paragraph() r = p.add_run() r.add_picture("Unbenannt.png") details = {"Coffee": 12, "Noodle": 23, "Soup": 123} context = {"details": details} doc.render(context) doc.save("Test.docx")