问题
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