django操作word全程实录讲解(包含操作图片,内含代码下载地址)

目的

数据已经存储在django数据库中,现在希望将数据库中的数据按照特定字段导入到word中,实现数据的动态写入。同时提供下载方法给前端用户。

环境

python 3.6.1

django 1.11.14

pillow 5.2.0

docxtpl 0.5.0

djangorestframework 3.8.2
 

系统为win7 64位,word版本为2007(劲量为word2007,其他版本可能会出问题)

步骤

1.  新建django项目,在根目录下放置word模板文件“train.docx”

2 .  安装上述python安装包

pip install 。。。。

3. 修改前端html文件

{% extends "app/layout.html" %}

{% block content %}

<div class="jumbotron">
    <h1>测试</h1>    
    <p><a href="{% url 'downloadreport' %}" class="btn btn-primary btn-large">生成word并下载</a></p>
</div>

{% endblock %}

4 . 修改url.py文件

urlpatterns = [
    # Examples:
    url(r'^$', app.views.home, name='home'),
    url(r'^downloadreport', app.views.downloadreport, name='downloadreport'),
    
]

5. 修改views.py文件

"""
Definition of views.
"""

from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime

#新添加的用于报表的文件
import os
from django.http import StreamingHttpResponse
from django.utils.translation import ugettext_lazy as _
from rest_framework.response import Response
from rest_framework.decorators import api_view
from docxtpl import DocxTemplate
from docxtpl import InlineImage
from docx.shared import Mm, Inches, Pt


def home(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/index.html',
        {
            'title':'Home Page',
            'year':datetime.now().year,
        }
    )


# 流方式读取文件
def read_file(file_name, size):
    with open(file_name, mode='rb') as fp:
        while True:
            c = fp.read(size)
            if c:
                yield c
            else:
                break


@api_view(['GET'])
def downloadreport(request):
    
    filename = 'test.docx'        # 所生成的word文档需要以.docx结尾,文档格式需要
    filepath = 'D://'
    template_path = os.getcwd() + '/train.docx'
    template = DocxTemplate(template_path)
    context1 = { 'chengyun' : "World company",
               'myimage': InlineImage(template, 'D:\\ceshi.jpg', width=Mm(30), height=Mm(60)), }
    template.render(context1)
    

    template.save(os.path.join(filepath,filename))
    response = StreamingHttpResponse(read_file(os.path.join(filepath, filename), 512))
    response['Content-Type'] = 'application/msword'
    response['Content-Disposition'] = 'attachment;filename="{}"'.format(filename)
    # time.sleep(10)
    return response
    

这里,我把图片命名为"ceshi.jpg"并且放在了D盘,在项目根目录的train.docx中添加了模板标签{{chengyun}}和{{myimage}}

然后采用django进行文字和图片的替换,同时图片给了长宽的参数用来进行图像尺寸的动态调整。文件读取方式采用了流读取方式,512字节的一个流。

整个项目采用VS2015在windows下开发,VS下安装django教程网址:https://mp.csdn.net/postedit/81103532

当然,采用其他IDE直接将该项目跑起来也没有问题。这里给出整个测试工程的代码地址

https://download.csdn.net/download/qianbin3200896/10621095

猜你喜欢

转载自blog.csdn.net/qianbin3200896/article/details/81974010
今日推荐