如何使用Django框架创建docx文件? [英] How to create a docx file using django framework?
问题描述
我想使用Django创建docx文件.我已经在笔记本电脑上安装了python-docx,我使用了pip install python-docx这个命令,甚至在桌面上创建了一个.docx文件,但是我不打算在django项目中使用它.首先,我是否需要从项目中修改settings.py才能将python-docx导入django?顺便说一句,当有人访问我的url应用程序时,我想创建这些文件,我有一个名为"planeaciones"的应用程序,这些是我的主要文件:
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'),
]
索引模板
{% 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 %}
推荐答案
这对我有用
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
这篇关于如何使用Django框架创建docx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!