• excel 导入数据库


    Django上传excel表格并将数据写入数据库:

    上传文件:

    .配置 setting.py 
    
    # 文件上传配置
    UPLOAD_ROOT = os.path.join(BASE_DIR,'upload')
    
    前端:
    使用 <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 %}
    
    后端:
    @csrf_exempt
    def upload(request):
        # 根name取 file 的值
        file = request.FILES.get('file')
        logger.log().info('uplaod:%s'% file)
        # 创建upload文件夹
        if not os.path.exists(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 in file.readlines():
                    f.write(i)
        except Exception as e:
            return HttpResponse(e)
    
    
        return HttpResponse('上传成功')
    

    解析excel 导入数据库:

    # 将excel数据写入mysql
    def wrdb(filename):
        # 打开上传 excel 表格
        readboot = xlrd.open_workbook(settings.UPLOAD_ROOT + "/" + filename)
        sheet = readboot.sheet_by_index(0)
        #获取excel的行和列
        nrows = sheet.nrows
        ncols = sheet.ncols
        print(ncols,nrows)
        sql = "insert into working_hours (jobnum,name,workingtime,category,project,date,createtime) VALUES"
        for i in range(1,nrows):
            row = sheet.row_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,datetime.datetime.now())
            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 = request.FILES.get('file')
        print('uplaod:%s'% file)
        # 创建upload文件夹
        if not os.path.exists(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 in file.readlines():
                    f.write(i)
    
            # 写入 mysql
            wrdb(file.name)
        except Exception as e:
            return HttpResponse(e)
    
        return HttpResponse('导入成功')
    
  • 相关阅读:
    Rebuilding a heap
    Comparison Operators Modified by ANY, SOME, or ALL
    个人外包项目全记 Best Partner
    你需要明白的索引和约束的前缀(AK,PK,IX,CK,FK,DF,UQ)
    This Android SDK requires Android Developer Toolkit version 17.0.0 or above!!(SDk版本一致)解决办法:
    web端获取系统当前时间
    This Android SDK requires Android Developer Toolkit version 17.0!!(SDk版本一致)解决办法:
    The configuration may be corrupt or incomplete解决方案
    SSH框架
    sdk下proguard.cfg文件找不到的解决办法
  • 原文地址:https://www.cnblogs.com/shaozheng/p/12889888.html
Copyright © 2020-2023  润新知