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 %}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM