在django中生成MS word文档 [英] Generate the MS word document in django

查看:620
本文介绍了在django中生成MS word文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在以pdf格式生成报告。但现在我想以ms字或docx格式生成报告。



我的api.py文件

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

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



在选项1中的选项:
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):

位置s.append(& markers = color:red | label:S |++ str(option.gps_longitude)+,+ str(option.gps_latidtude)+)
位置:
out_string + = loc

如果位置:
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 = link_callback = fetch_resources)
如果不是pdf.err:
返回结果
其他:
返回无

我得到结果中的所有数据,然后将该数据导出到pdf。但是现在我想将数据导出到docx或MS word格式。我想要导出为docx格式的结果相同。
因为我以pdf格式获取数据,所以我不想将导出的pdf转换为docx。我想直接在docx导出。
我尝试使用python-docx,但不能弄清楚如何以docx格式导出。
任何人都可以指导我如何做到这一点。我应该在django使用哪个模块。
请帮助我

解决方案

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

  from docx import * 
from docx.shared import Inches

def TestDocument(request):

document = Document()
docx_title =TEST_DOCUMENT.docx
#----封面信件----
document.add_picture((r'%s /static/images/my-header.png'%(settings.PROJECT_PATH)),width = Inches(4))
document.add_paragraph()
document.add_paragraph(%s%date。今天()。strftime('%B%d,%Y'))

document.add_paragraph('尊敬的先生或女士:')
document.add_paragraph('我们很高兴帮助您使用您的小部件。)
document.add_paragraph('请随时与我联系获取任何其他信息。)
document.add_paragraph('我期待在此项目中协助您。 )

document.add_paragraph()
document.add_parag raph('最好的问候')
document.add_paragraph('Acme Specialist 1)')
document.add_page_break()

#准备下载文件
# -----------------------------
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


Currently i am generating the reports in pdf format. But now i want to generate the reports in ms word or docx format.

my api.py file

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

I am getting all the data in result and then exporting that data to pdf. But now i want to export the data to the docx or MS word format. The same result i want to export to docx format. As i am getting the data in pdf format so i dont want to convert that exported pdf to docx. I want to export directly in docx. I tried using python-docx, but not able to figure out how to export out in docx format. Can anyone guide me how to this. Which modul i should use in django. Please help me

解决方案

Here is how I generate a docx file from within a Django view:

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

这篇关于在django中生成MS word文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆