zoukankan      html  css  js  c++  java
  • python之路_excel批量导入数据

    批量导入excel文件中的数据,我们需要借助xlrd模块,示例如下:

      视图代码:

    import xlrd
    def multi_view(self,request):
        """
        批量导入
        :param request: 
        :return: 
        """
        if request.method == 'GET':
            return render(request,'multi_view.html')
        else:
            file_obj = request.FILES.get('exfile')
            with open('xxxxxx.xlsx',mode='wb') as f:
                for chunk in file_obj:
                    f.write(chunk)
           
            workbook = xlrd.open_workbook('xxxxxx.xlsx')
           
            sheet = workbook.sheet_by_index(0)            #拿到excel中的第一个文件薄
            maps = {
                0:'name',
                1:'qq',
            }
            #maps是关于excel表中应该有的字段和字段顺序
            for index in range(1,sheet.nrows):            #对数据行进行循环(不包含第一行的字段行)
                row = sheet.row(index)                    #获得行的列对象
                row_dict = {}
                for i in range(len(maps)):
                    key = maps[i]
                    cell = row[i]
                    row_dict[key] = cell.value            #cell.value获得列中的内容
                print(row_dict)
               #将数据录入数据库,如:UserInfo.objects.create(**row_dict)
            return HttpResponse('上传成功')

      页面代码:

    {% extends 'stark/layout.html' %}
    
    {% block body %}
        <h1 >批量导入数据</h1>
    {# 为了用户批量上传的文件数据按照我们视图代码中要求的那些字段格式,我们可以提供这样的模板excel#}
        <a href="/static/xxx.xlsx">下载模板</a>   
        <form method="post" enctype="multipart/form-data" class="form-horizontal" novalidate>
            {% csrf_token %}
            <input type="file" name="exfile">
    
            <input type="submit" value="提交">
        </div>
        </form>
    {% endblock %}
  • 相关阅读:
    Balanced Binary Tree
    Swap Nodes in Pairs
    Reverse Nodes in k-Group
    Reverse Linked List II
    Remove Nth Node From End of List
    Remove Duplicates from Sorted List II
    Remove Duplicates from Sorted List
    Partition List
    Merge Two Sorted Lists
    【Yii2.0】1.2 Apache检查配置文件语法
  • 原文地址:https://www.cnblogs.com/seven-007/p/8542896.html
Copyright © 2011-2022 走看看