代码改变世界

python 使用pymysql上传excel数据

2021-02-27 22:09  ttym88m  阅读(217)  评论(0编辑  收藏  举报
from django.shortcuts import render, HttpResponse
from Day72bbs.settings import MEDIA_ROOT
from docxtpl import DocxTemplate
import os
import xlrd
MEDIA_ROOT  在 settings.py 中的设置为 
MEDIA_URL='/doctemplates/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'doctemplates')


'''
将数据插入数据库
wrdb
'''

def wrdb(filename):
readboot = xlrd.open_workbook(MEDIA_ROOT +'/' + r'uploadfile/' + filename)
sheet = readboot.sheet_by_index(0)
nrows = sheet.nrows
ncols = sheet.ncols
print("*"*100)
print(nrows,ncols)
print("*" * 100)

sql = " insert into tab_exportexcel (name,gender,minzu,idcard," \
"phone,email,phone2,edu1,edu2,edu3,skill1,skill2) values "

for i in range(1,nrows):
row = sheet.row_values(i)
name=str(row[0]).strip("'")
gender=str(row[1]).strip("'")
minzu=str(row[2]).strip("'")
idcard=str(row[3]).strip("'")
phone=str(row[4]).strip("'")
email=str(row[5]).strip("'")
phone2=str(row[6]).strip("'")
edu1=str(row[7]).strip("'")
edu2=str(row[8]).strip("'")
edu3=str(row[9]).strip("'")
skill1=str(row[10]).strip("'")
skill2=str(row[11]).strip("'")
values = "( '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s' ,'%s')"%(name,gender,minzu,idcard,phone,email,phone2,edu1,edu2,edu3,skill1,skill2)
sql = sql + values +","

sql = sql[:-1]
print(sql)

import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root',
password='123', database='day64',
port=3306, charset='utf8mb4')
cursor = conn.cursor()
try:
cursor.execute(sql)
conn.commit()
except Exception :
conn.rollback()
finally:
cursor.close()
conn.close()


# print(sql)






def upload(request):
if request.method=="POST":
file = request.FILES.get('file')
if not os.path.exists(MEDIA_ROOT):
os.makedirs(MEDIA_ROOT)

try:
if file is None:
return HttpResponse("请选择要上传的文件")

print(MEDIA_ROOT +'/' + r'uploadfile/')
print(file.name)
with open(MEDIA_ROOT +'/' + r'uploadfile/' + file.name,'wb') as f:
for i in file.readlines():
f.write(i)
wrdb(file.name)

except Exception as e:
return HttpResponse(e)

return HttpResponse('文件上传成功')

if request.method=="GET":
return render(request,"uploadExcel.html")