django 上传xlsx表格,并显示在前端页面上。

选择上传文件

<form action="/device-info-management/device-management/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="form-group">
        <input type="file"
           title="Upload excel file"
           name="excel_file"
           style="border: 1px solid black; padding: 5px;"
           required="required">
    </div>

    <div class="form-group">
        <input type="submit"
           value="Upload"
           style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;">
    </div>

</form>

后端选择文件进行处理

def upload_excel(request):
    if request.session.get('username') is None:
        return render(request, 'user/login.html')
    if "GET" == request.method:
        return render(request, 'device_info_management/device.html', {})
    elif "POST" == request.method:
        excel_file = request.FILES["excel_file"]
        print(excel_file)
        # you may put validations here to check extension or file size

        wb = openpyxl.load_workbook(excel_file)


        # getting a particular sheet by name out of many sheets
        worksheet = wb["Sheet1"]
        print(worksheet)

        excel_data = list()
        # iterating over the rows and
        # getting value from each cell in row
        for row in worksheet.iter_rows():
            row_data = list()
            for cell in row:
                row_data.append(str(cell.value))
            excel_data.append(row_data)
        global global_excel_data
        global_excel_data = excel_data
        return render(request, 'device_info_management/device.html', {"excel_data":excel_data})

通过模板变量进行文件展示

<table class="table">
  <thead>
    <tr>
     
    </tr>
  </thead>
  <tbody>
    {% for row in excel_data %}
        <tr>
            {% for cell in row %}
                <td>{{ cell }}</td>
            {% endfor %}
        </tr>
    {% endfor %}

  </tbody>
</table>

你可能感兴趣的:(django 上传xlsx表格,并显示在前端页面上。)