当前位置: 首页>>代码示例>>Python>>正文


Python DocxTemplate.save方法代码示例

本文整理汇总了Python中docxtpl.DocxTemplate.save方法的典型用法代码示例。如果您正苦于以下问题:Python DocxTemplate.save方法的具体用法?Python DocxTemplate.save怎么用?Python DocxTemplate.save使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在docxtpl.DocxTemplate的用法示例。


在下文中一共展示了DocxTemplate.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: DocxTemplate

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [as 别名]
from docxtpl import DocxTemplate
import jinja2

doc = DocxTemplate("TemplateLGULiPADAccountRegistration.docx")
context = { 'Municipality' : "Munishipariti" }
doc.render(context)
doc.save("generated_doc.docx")
开发者ID:PhilLidar-DAD,项目名称:lgu-scripts,代码行数:9,代码来源:sample-todoc.py

示例2: run

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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)
开发者ID:MedinaAlex,项目名称:Lumiplan,代码行数:31,代码来源:writeOnTemplate.py

示例3: download

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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
开发者ID:SicunStudio,项目名称:aunet-flask,代码行数:36,代码来源:views.py

示例4: gen_a_doc

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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"
开发者ID:ChubChubs,项目名称:SecretaryDEK,代码行数:33,代码来源:generator.py

示例5: export_to_word

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [as 别名]
 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')],
                                      )
开发者ID:baodan,项目名称:abc_ipt,代码行数:13,代码来源:controllers.py

示例6: import_excel

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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
开发者ID:baodan,项目名称:abc_ipt,代码行数:54,代码来源:controllers.py

示例7: test

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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')
开发者ID:dvstrom,项目名称:gooderp_addons,代码行数:16,代码来源:report_helper.py

示例8: create_source_docx

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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)
开发者ID:JasonAxesen,项目名称:gooderp_addons,代码行数:18,代码来源:report_docx.py

示例9: document_creator

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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()
开发者ID:LeXuZZ,项目名称:dj_docs,代码行数:18,代码来源:subscribers.py

示例10: memo_docx

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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
开发者ID:msarabi95,项目名称:easy-internship,代码行数:47,代码来源:views.py

示例11: run

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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)
开发者ID:MedinaAlex,项目名称:Lumiplan,代码行数:20,代码来源:writeOnTemplate.py

示例12: create_source_docx

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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)
开发者ID:jaronemo,项目名称:gooderp_addons,代码行数:22,代码来源:report_docx.py

示例13: create_source_docx

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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
开发者ID:yanshaozhi,项目名称:gooderp_addons,代码行数:25,代码来源:report_docx.py

示例14: convert

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [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
开发者ID:b0tting,项目名称:qfoon,代码行数:26,代码来源:RFCConverter.py

示例15:

# 需要导入模块: from docxtpl import DocxTemplate [as 别名]
# 或者: from docxtpl.DocxTemplate import save [as 别名]
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')
开发者ID:aydarvpro,项目名称:python-docx-template,代码行数:17,代码来源:dynamic_table.py


注:本文中的docxtpl.DocxTemplate.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。