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>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要将XLS文件保存数据库中,可以按照以下步骤进行操作: 1. 首先需要安装 xlrd 库,它可以读取 Excel 文件。可以在命令行中输入以下命令进行安装: ``` pip install xlrd ``` 2. 在 Django 项目中创建一个模型,用于存储 Excel 文件的内容。可以使用二进制字段(BinaryField)来存储文件内容。 ```python from django.db import models class ExcelFile(models.Model): file = models.BinaryField() ``` 3. 创建一个视图,用于处理上传文件的请求。在视图中,可以使用 xlrd 库读取 Excel 文件的内容,并将其存储数据库中。 ```python import xlrd from django.shortcuts import render from .models import ExcelFile def upload_file(request): if request.method == 'POST': file = request.FILES['file'] excel = xlrd.open_workbook(file_contents=file.read()) sheet = excel.sheet_by_index(0) rows = [] for i in range(sheet.nrows): rows.append(sheet.row_values(i)) excel_file = ExcelFile(file=file.read()) excel_file.save() return render(request, 'success.html', {'rows': rows}) return render(request, 'upload.html') ``` 在这个视图中,首先从请求对象中获取上传的文件,然后使用 xlrd 库打开 Excel 文件并读取其内容。将读取到的内容存储到一个列表中,最后将文件内容保存数据库中。 4. 创建一个 HTML 模板,用于上传 Excel 文件。可以使用 Django 的表单组件来实现上传文件的功能。 ```html {% extends 'base.html' %} {% block content %} <h1>Upload Excel File</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <button type="submit">Upload</button> </form> {% endblock %} ``` 在模板中,使用表单组件来实现上传文件的功能。在表单中,需要设置 enctype 属性为 multipart/form-data,这样才能上传二进制文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

huanghong6956

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

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

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

打赏作者

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

抵扣说明:

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

余额充值