Django upload excel file

Keywords: Excel Database Attribute JSON

Install the module first

pip3 install xlrd install xlrd package to parse table data

Create the upload folder in the sub application statistics directory, Then go to settings.py To configure

UPLOAD_ROOT = os.path.join(BASE_DIR,'upload')

When there is an upload file in the form, the picture / form file can be submitted as follows

<form id="form1" enctype="multipart/form-data">
         
           	<p><label for="">Class name</label>
            <input type="text" name="name" placeholder="Example: H1808C"></p>
            <input type="file" name="file"></p>
        
           
            <button type="button" onclick="exportin()">Import</button>

        </form>

The function of the following method can pass all the values in the form, but when uploading a file, the form above must write the attribute enctype = "multipart / form data"

<script>
    function exportin(){
        $.ajax({
            url:"/exportin/",
            type:"post",
            cache: false,
            data: new FormData($('#form1')[0]),
            processData: false,
            contentType: false,
            dataType:"json",
            success:function(res){
                if(res.code==200){
                    alert(res.mes)
                    window.location.href="/index/"
                }else{
                    alert(res.mes)
                }
               
            }
        })
    }

</script>

Background code, write file operation

# First, introduce the configuration settings
from jiyun import settings
# Root name takes the value of file
file = request.FILES.get('file')

# Loop binary write the path of settings configuration in brackets
with open(settings.UPLOAD_ROOT+"/"+file.name,'wb') as f:
              for i in file.readlines():
                   f.write(i)

Open file operation

# Open local file
excel = xlrd.open_workbook(settings.UPLOAD_ROOT+"/"+file.name)
excel.sheet_names()

#  Get the value of sheet by index (0) with subscript 0
sheet = excel.sheet_by_index(0)
#	Sheet.row [values (1) the value of the current subscript. You can print it out and see it
print(sheet.row_values(1))

#	Total number of sheet.nrows total number of sheet.ncols
print(sheet.nrows)
print(sheet.ncols)

The above is uploaded to the local area and opened to view value. If you want to enter the database, because the file has a lot of data, it is not suitable to operate the database in sequence. You should encapsulate the data to enter the database once

sql_list = []
 # Traverse from 1 subscript to the total number of Student tables
for i in range(1,sheet.nrows):
        sql_list.append(Student(name=sheet.row_values(i)[0],class_id=c.id))
Student.objects.bulk_create(sql_list)

Posted by chris1 on Thu, 05 Dec 2019 08:24:45 -0800