django-连接mysql-xls文件上传保存数据库-数据库下载为xls

from django.shortcuts import render

# Create your views here.
import os,uuid
from io import BytesIO
f = BytesIO()
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.models import User
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate,login,logout
from django.contrib import messages

import xlrd,xlwt
from app.models import Project

import time
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def shangchuan(request):
    if request.POST:
        ff=request.FILES.get('filepath')
        print(ff)
        if ff==None:
            msg='未上传任何文件'
            return render(request, 'import.html',locals())
        else:
            filename = ff.name
            filetype = filename.split('.')[-1]
            print(filename)
            print(filetype)
            leixing=['xls','xlsx','xlt']

            if filetype in leixing:
                uploadpath = "app/static/file"
                if not os.path.exists(uploadpath):
                    os.mkdir(uploadpath)
                uploadname = str(uuid.uuid1()) + "." + filetype
                path = uploadpath + os.sep + uploadname
                with open(path, "wb+") as fp:
                    for chunk in ff.chunks():
                        fp.write(chunk)
                path
                print('添加成功')
                msg = '上传成功'
                return render(request, 'import.html', locals())
            else:
                msg='文件格式错误'
                return render(request, 'import.html',locals())

        return render(request,'import.html')
    else:
        return render(request,'import.html')

def duqu(request):
    if request.POST:
        ff = request.FILES.get('filepathd')
        print(ff)
        if ff == None:
            msg = '未上传任何文件'
            return render(request, 'duqu.html', locals())
        else:
            filename = ff.name
            filetype = filename.split('.')[-1]
            print(filename)
            print(filetype)
            leixing = ['xls', 'xlsx', 'xlt']

            if filetype in leixing:
                uploadpath = "app/static/file"
                if not os.path.exists(uploadpath):
                    os.mkdir(uploadpath)
                uploadname = str(uuid.uuid1()) + "." + filetype
                path = uploadpath + os.sep + uploadname
                with open(path, "wb+") as fp:

                    for chunk in ff.chunks():
                        fp.write(chunk)

                print('添加成功')
                filepath ='app/static/file/' + uploadname

                # 地址前用'\'转译符要加
                workbook = xlrd.open_workbook(filepath)
                # 提取表格名称
                sheets = workbook.sheet_names()
                # 提取第一个表格内容
                worksheet = workbook.sheet_by_name((sheets[0]))
                # 统计有多少行
                worksheet.nrows
                # 统计有多少列
                worksheet.ncols
                # 遍历所以单元格
                book=[]
                for i in range(worksheet.nrows):
                    for j in range(7):
                        book.append(worksheet.cell_value(i, j))

                    Project.objects.create(bookid=book[0],isbn=book[1],bookname=book[2],zuozhe=book[3],chubanshe=book[4],chubanriqi=book[5],jiage=book[6])
                    book=[]
                msg = '上传成功'
                return render(request, 'duqu.html', locals())
            else:
                msg = '文件格式错误'
                return render(request, 'duqu.html', locals())

        return render(request, 'duqu.html')
    else:
        return render(request, 'duqu.html')

def show(request):
    booklist=Project.objects.all()
    return render(request, 'show.html', locals())


from django.http import StreamingHttpResponse
def xiazai(request):
    pplist=Project.objects.all()
    plist=[]
    for pp in pplist:
        listd=[]
        listd.append(pp.bookid)
        listd.append(pp.isbn)
        listd.append(pp.bookname)
        listd.append(pp.zuozhe)
        listd.append(pp.chubanshe)
        listd.append(pp.chubanriqi)
        listd.append(pp.jiage)
        plist.append(listd)

    print(plist)
    uploadname = str(uuid.uuid1()) + ".xls"

    filepath = 'app/static/file/{0}'.format(uploadname)
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet('sheet1')

    for j in range(0, len(plist)):
        for i in range(7):
            sheet.write(j, i, plist[j][i])

    workbook.save(filepath)
    print('保存成功')


    def fileiter(path, chunk=512):
        with open(path, 'rb')as filed:
            while True:
                content = filed.read(chunk)
                if content:
                    yield content
                else:
                    break
    response = StreamingHttpResponse(fileiter(filepath))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename={0}'.format(uploadname)
    return response


 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
    <script src="{% static 'jquery-3.2.1.min.js' %}"></script>
    <script src="{% static 'jquery.cookie.js' %}"></script>
    <script>
        $(function () {



        });
    </script>
</head>
<body>
<form method="post" action="/duqu/" enctype="multipart/form-data">
    {% csrf_token %}

    <input type="file" name="filepathd" ><span style="color: red">{{ msg }}</span><br>


    <button type="submit" onclick="return confirm('请确认');">提交</button>

</form>



</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

huanghong6956

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值