CSV文件到Django模板中

时间:2019-03-07 02:15:00

标签: django

我有一个使用FileField()上传文件的应用程序。上传文件效果很好,但是我对如何将CSV文件内容显示到HTML表中存在问题,其中标题转到表标题,而CSV文件的行/行转到HTML表中的适当单元格。

目前,我在检索CSV文件的列方面取得了一些成功。这些是片段。

方法:

# retrieve datafarame's columns
def get_columns(file):
    df = pd.read_csv(file)
    cols = df.columns
    return cols

HTML:

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
            <thead>
                <tr>
                    {% for col in columns %}
                    <th>{{ col }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                <tr>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
            </tbody>
        </table>

2 个答案:

答案 0 :(得分:0)

如果您在后端使用熊猫,则可以从视图中传递dataframe.to_dict(),这将为您提供字典列表。您可以遍历模板中的行列表。

views.py

def myview(request):
    df = pd.read_csv(file)
    return render(request, 'my_view.html', {'columns': df.columns, 'rows': df.to_dict('records')})

template.html

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
        <thead>
            <tr>
                {% for col in columns %}
                <th>{{ col }}</th>
                {% endfor %}
            </tr>
        </thead>
        <tbody>
            {% for index, row in rows %}
                <tr>
                  <td>{{row.name}}</td>
                  <td>{{row.email</td>

                </tr>
             {% endfor %}
        </tbody>
    </table>

答案 1 :(得分:0)

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Detect Outliers</title>
    </head>
    <body>
        <button type="button">Upload</button> 
        <h1>Uploaded Data</h1> 
        <table border="1px"> 
            <tr> 
                {% for data in DataFrame %} 
                    <th>{{ data }}</th> 
                {% endfor %} 
         
                {% for _, record in DataFrame.iterrows %} 
                    <tr> 
                        {% for value in data %} 
                            <td>{{ value }}</td> 
                        {% endfor %} 
                    </tr> 
                {% endfor %} 
            </tr> 
        </table> 
    </body>
    </html>
相关问题