zoukankan      html  css  js  c++  java
  • python 使用pymysql上传excel数据

    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")
  • 相关阅读:
    关于modelsim的波形文件(vsim.wlf)(转自http://www.eefocus.com/ican/blog/1010/196941_ebbde.html)
    c++ 头文件 再学习
    c++头文件和#include 学习笔记
    C++中嵌入汇编(vs)
    cocos2dx plist使用
    OpenGL 前凑
    别人的经验和自己现在的疑惑
    C++ 枚举类型
    cocos2dx draw & update
    const对象分析
  • 原文地址:https://www.cnblogs.com/ttym88m/p/14457406.html
Copyright © 2011-2022 走看看