inputtypefile不上传文件Django上传excel表格并将数据写⼊数据库
前⾔:
  最近公司领导要统计技术部门在各个业务条线花费的⼯时百分⽐,⽽ jira 当前的 Tempo 插件只能统计个⼈⼯时。于是就写了个报表⼯具,将 jira 中导出的个⼈⼯时excel表格导⼊数据库,在后端处理各个业务⼯时占⽐。后来研究了 jira 的 API ⽂档,放弃了之前的思路,直接调⽤ jira  API 处理数据,这个先不谈。这篇博客主要介绍 Django 上传⽂件,然后解析 excel 导⼊数据库。
⼀、上传⽂件:
将⽂件上传到服务器指定路径,其实很简单,⼀共有三个步骤:
1.配置 setting.py
# ⽂件上传配置
UPLOAD_ROOT = os.path.join(BASE_DIR,'upload')
2.前端代码如下,使⽤ <form> 表单提交,"/upload/" 路由配置在 urls 中,这个就不再多说了。
{% extends 'base.html' %}
{% block content %}
<body>
<form id="form"  enctype="multipart/form-data" action="/upload/" method="post">
<p><input type="file"  name="file"></p>
<input type="submit" name="提交">
</form>
</body>
{% endblock %}
3.后端代码如下,这段代码可以上传任意格式的⽂件,没有校验⽂件类型。
@csrf_exempt
def upload(request):
# 根name取 file 的值
file = ('file')
logger.log().info('uplaod:%s'% file)
# 创建upload⽂件夹
if not ists(settings.UPLOAD_ROOT):
os.makedirs(settings.UPLOAD_ROOT)
try:
if file is None:
return HttpResponse('请选择要上传的⽂件')
# 循环⼆进制写⼊
with open(settings.UPLOAD_ROOT + "/" + file.name, 'wb') as f:
for i adlines():
f.write(i)
except Exception as e:
return HttpResponse(e)
return HttpResponse('上传成功')
⼆、解析 excel  导⼊数据库
1.⽂件上传结束后,接下来读取刚上传到服务器的 excel 表格,然后写⼊数据库。所以整个后端代码是这样的:
# 将excel数据写⼊mysql
def wrdb(filename):
# 打开上传 excel 表格
readboot = xlrd.open_workbook(settings.UPLOAD_ROOT + "/" + filename)
sheet = readboot.sheet_by_index(0)
#获取excel的⾏和列
nrows = ws
ncols = ls
print(ncols,nrows)
sql = "insert into working_hours (jobnum,name,workingtime,category,project,date,createtime) VALUES"
for i in range(1,nrows):
row = w_values(i)
jobnum = row[4]
name = row[5]
workingtime = row[2]
category = row[8]
project = row[1]
date = xldate_as_datetime(row[3],0).strftime('%Y/%m/%d')
values = "('%s','%s','%s','%s','%s','%s','%s')"%(jobnum,name,workingtime,category,project,date,w())
sql = sql + values +","
 # 为了提⾼运⾏效率,⼀次性把数据 insert 进数据库 
sql = sql[:-1]
# 写⼊数据库
# DataConnection 是⾃定义的公共模块,⽤的是第三⽅库,⽤来操作数据库。没有⽤ ORM ,后续有 group by 等复杂 sql 不好操作。    DataConnection.MysqlConnection().insert('work',sql)
@csrf_exempt
def upload(request):
# 根name取 file 的值
file = ('file')
print('uplaod:%s'% file)
# 创建upload⽂件夹
if not ists(settings.UPLOAD_ROOT):
os.makedirs(settings.UPLOAD_ROOT)
try:
if file is None:
return HttpResponse('请选择要上传的⽂件')
# 循环⼆进制写⼊
with open(settings.UPLOAD_ROOT + "/" + file.name, 'wb') as f:
for i adlines():
f.write(i)
# 写⼊ mysql
wrdb(file.name)
except Exception as e:
return HttpResponse(e)
return HttpResponse('导⼊成功')
2.数据导⼊后,通过⼀些处理就得到了我们想要的数据。报表其中之⼀的饼图: