如何使用django框架创建docx文件?

时间:2018-01-23 08:13:30

标签: python django docx python-docx

我想使用django创建一个docx文件。我已经在我的笔记本电脑上安装了python-docx,我使用了这个命令pip install python-docx,我甚至在我的桌面上创建了一个.docx文件,但我不知道如何在我的django项目中使用它。首先,我是否需要从我的项目中修改settings.py才能将python-docx导入到django?顺便说一句,当有人访问我的网址应用时,我想创建这些文件我有一个名为'planeaciones'的应用程序,这些是我的主要文件:

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 %}

1 个答案:

答案 0 :(得分:1)

这对我有用

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