How to create a docx file using django framework?

混江龙づ霸主 提交于 2020-08-26 10:16:08

问题


I want to create a docx file using django. I have already installed python-docx on my laptop, I used this command pip install python-docx and I even created a .docx file on my desktop but I do not how to use this on my django project. First of all, do I need modify settings.py from my project in order to import python-docx to django? by the way I want to create these files when someone visit my urls app I have an app called 'planeaciones' and these are my main files:

views.py

from django.http import HttpResponse

from django.shortcuts import render

def index(request):
    return render(request, 'planeaciones/index.html')

urls.py

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

index template

{% extends 'base.html' %}

{% block title %}Planeaciones{% endblock %}

{% block content %}

  <h3 class="text-center">Mis planeaciones</h3>
<p></p>
{% if user.is_superuser %}
  <p>Hola Administrador</p>

{% endif %}


{% endblock %}

回答1:


Well this worked for me

views.py

# Create your views here.
from django.http import HttpResponse

from django.shortcuts import render



from django.http import HttpResponse
from docx import Document
from docx.shared import Inches


def index(request):
    document = Document()

    document.add_heading('Document Title', 0)

    p = document.add_paragraph('A plain paragraph having some ')
    p.add_run('bold').bold = True
    p.add_run(' and some ')
    p.add_run('italic.').italic = True

    document.add_heading('Heading, level 1', level=1)
    document.add_paragraph('Intense quote', style='IntenseQuote')

    document.add_paragraph(
    'first item in unordered list', style='ListBullet'
    )
    document.add_paragraph(
    'first item in ordered list', style='ListNumber'
    )

    #document.add_picture('monty-truth.png', width=Inches(1.25))

    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Qty'
    hdr_cells[1].text = 'Id'
    hdr_cells[2].text = 'Desc'

    document.add_page_break()

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=download.docx'
    document.save(response)


    return response


来源:https://stackoverflow.com/questions/48396953/how-to-create-a-docx-file-using-django-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!