【问题标题】:Display CSV Contents in a Table using Views/Template使用视图/模板在表格中显示 CSV 内容
【发布时间】:2017-08-17 15:45:50
【问题描述】:

我正在创建一个用户可以上传 csv 文件的网站,并且目前正在开发一个用户无需下载即可查看文件内容的页面。为此,我正在像这样的视图中读取 csv:

def source_details(request, source_id):
    context_dict = {}

    # Get a specific object
    data_source = Source.objects.get(id=source_id)
    context_dict['data_source'] = data_source

    # Open the csv and print it to terminal
    with open(MEDIA_ROOT+data_source.sample, newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in spamreader:
            print(', '.join(row))


    return render(request, 'data/source-details.html', context_dict)

如您所见,到目前为止,我打开上传的 csv 文件并将其打印到终端没有问题,但是我想在浏览器中将其显示为表格。关于我如何做到这一点的任何想法?谢谢。

【问题讨论】:

    标签: django csv django-templates django-views


    【解决方案1】:

    您可能希望列出如下列表:

    csv_preform = [[row1],[row2],[row3]]
    

    然后将它传递给上下文并在模板中循环它:

    <table>
    <tr>
        <th>Test1</th>
        <th>Test2</th>
             ...
    </tr>
    
    {% for row in csv_preform %}
    <tr>
        {% for sub_row in row %}
            <td>{{sub_row}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-09
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      相关资源
      最近更新 更多