Search code examples
pythondjangodjango-viewspython-docx

How to send data into word document with Django?


I'm using Django I want to send some data from my database to a document word, I'm using Python-Docx for creating word documents I use the class ExportDocx it can generate a static word file but I want to place some dynamic data (e.g. product id =5, name=""..) basically all the details to the "product" into the document

class ExportDocx(APIView):
  def get(self, request, *args, **kwargs):
    queryset=Products.objects.all()
    # create an empty document object
    document = Document()
    document = self.build_document()

    # save document info
    buffer = io.BytesIO()
    document.save(buffer)  # save your memory stream
    buffer.seek(0)  # rewind the stream

    # put them to streaming content response 
    # within docx content_type
    response = StreamingHttpResponse(
        streaming_content=buffer,  # use the stream's content
        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )

    response['Content-Disposition'] = 'attachment;filename=Test.docx'
    response["Content-Encoding"] = 'UTF-8'

    return response

 def build_document(self, *args, **kwargs):
    document = Document()
    sections = document.sections
    for section in sections:
        section.top_margin = Inches(0.95)
        section.bottom_margin = Inches(0.95)
        section.left_margin = Inches(0.79)
        section.right_margin = Inches(0.79) 

    # add a header
    document.add_heading("This is a header")

    # add a paragraph
    document.add_paragraph("This is a normal style paragraph")

    # add a paragraph within an italic text then go on with a break.
    paragraph = document.add_paragraph()
    run = paragraph.add_run()
    run.italic = True
    run.add_text("text will have italic style")
    run.add_break()
    
    return document

This is the URL.py of the

    path('<int:pk>/testt/', ExportDocx.as_view() , name='generate-testt'),

How can I generate it tho I think I need to make the data string so it can work with py-docx.

for the python-docx documentation: http://python-docx.readthedocs.io/


Solution

  • For a product record like: record = {"product_id": 5, "name": "Foobar"), you can add it to the document in your build_document()` method like:

    document.add_paragraph(
        "Product id: %d, Product name: %s"
        % (record.product_id, record.name)
    )
    

    There are other more modern methods for interpolating strings, although this sprintf style works just fine for most cases. This resource is maybe not a bad place to start.