在djang中生成MS-word文档

2024-05-14 02:55:55 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在生成pdf格式的报告。但现在我想用word或docx格式生成报告。

我的api.py文件

def export_pdf(request,id):
        report = Report.objects.get(id=id)                

        options1 = ReportPropertyOption.objects.filter(report=report,is_active=True)   
        locations = []  
        out_string = ""    
        map = None



        for option in options1:  
            option.property = get_property_name(option.property)        
            option.exterior_images = ReportExteriorImages.objects.filter(report = option)  
            option.interior_images = ReportInteriorImages.objects.filter(report = option)
            option.floorplan_images = ReportFloorPlanImages.objects.filter(report = option)
            option.fitouts =    ReportFitOut.objects.filter(propertyoption = option)   
            if (option.gps_longitude):

                locations.append("&markers=color:red|label:S|"+""+str(option.gps_longitude)+","+str(option.gps_latidtude)+"")
        for loc in locations:
            out_string+=loc

        if locations:
            map = "http://maps.google.com/maps/api/staticmap?center=Bangalore&zoom=12&size=512x512&maptype=roadmap"+out_string+"&sensor=true"              
        #map = "http://maps.google.com/maps/api/staticmap?zoom=12&size=400x400&maptype=roadmap&sensor=false&center=\\"
        html  = render_to_string('report/export.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request,{'options1':options1,'meta':report.meta,'map':map}))

        result = StringIO.StringIO()       
        pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources )        
        #pdf = Docx(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources )
        if not pdf.err:
            return result
        else:
            return None

我得到结果中的所有数据,然后将这些数据导出为pdf。但现在我想将数据导出为docx或MS-word格式。同样的结果我想导出为docx格式。 因为我得到的数据是pdf格式的,所以我不想把导出的pdf转换成docx。我想直接在docx中导出。 我试过使用python docx,但不知道如何以docx格式导出。 有人能指导我怎么做吗。我应该在django中使用哪个模块。 请帮帮我


Tags: reportmapstringobjectspdfhtml格式result
1条回答
网友
1楼 · 发布于 2024-05-14 02:55:55

下面是如何从Django视图中生成docx文件的:

from docx import *
from docx.shared import Inches

def TestDocument(request):

    document = Document()
    docx_title="TEST_DOCUMENT.docx"
    # ---- Cover Letter ----
    document.add_picture((r'%s/static/images/my-header.png' % (settings.PROJECT_PATH)), width=Inches(4))
    document.add_paragraph()
    document.add_paragraph("%s" % date.today().strftime('%B %d, %Y'))

    document.add_paragraph('Dear Sir or Madam:')
    document.add_paragraph('We are pleased to help you with your widgets.')
    document.add_paragraph('Please feel free to contact me for any additional information.')
    document.add_paragraph('I look forward to assisting you in this project.')

    document.add_paragraph()
    document.add_paragraph('Best regards,')
    document.add_paragraph('Acme Specialist 1]')
    document.add_page_break()

    # Prepare document for download        
    # -----------------------------
    f = StringIO()
    document.save(f)
    length = f.tell()
    f.seek(0)
    response = HttpResponse(
        f.getvalue(),
        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )
    response['Content-Disposition'] = 'attachment; filename=' + docx_title
    response['Content-Length'] = length
    return response

相关问题 更多 >