{% csrf_token %}
当前位置:   article > 正文

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

gradio上传excel并展示

选择上传文件

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

后端选择文件进行处理

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})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

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

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/94360
推荐阅读
相关标签