【问题标题】:django csv header and row format problemdjango csv标题和行格式问题
【发布时间】:2011-03-07 17:20:27
【问题描述】:

我正在尝试创建 csv 下载,但结果下载给了我不同的格式

def csv_download(request):
    import csv
    import calendar
    from datetime import *
    from dateutil.relativedelta import relativedelta

    now=datetime.today()
    month = datetime.today().month
    d = calendar.mdays[month]

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=somefilename.csv'
    m=Product.objects.filter(product_sellar = 'jhon')
    writer = csv.writer(response)
    writer.writerow(['S.No'])
    writer.writerow(['product_name'])
    writer.writerow(['product_buyer'])
    for i in xrange(1,d):

       writer.writerow(str(i) + "\t")



    for f in m:
         writer.writerow([f.product_name,f.porudct_buyer])

    return response

以上代码的输出:

product_name
1
2
4
5
6
7
8
9
1|10
1|1
1|2
.
.
.
2|7


mgm | x_name
wge | y_name

我是这样看的

s.no   porduct_name product_buyser  1     2   3   4   5   6   7   8 9 10 .....27 total
  1   mgm            x_name         2      3      8                                13
  2  wge             y_name                   4       9                            13

你能帮我下载上面的 csv 吗? 如果可能的话,你能告诉我最后如何总结所有个人用户总数吗?

例子:

我们有销售表,每天都会插入卖家信息

表格数据看起来像

 S.no product_name product_seller sold Date
  1     paint        jhon           5   2011-03-01
  2     paint        simth          6   2011-03-02 

我创建了一个表格,它以以下格式显示,我正在尝试创建 csv 下载

s.no prod_name   prod_sellar 1-03-2011  2-03-2011   3-03-2011   4-03-2011 total
    1     paint         john       10        15               0               0     25
    2     paint         smith      2          6               2               0     10

【问题讨论】:

  • 产品对象还有哪些其他字段?您只是在上面的示例代码中公开了 product_name 和 product_buyer。
  • 您是否只是在从数据库中获取对象之前确定的特定月份生成文件?
  • 是的,我正在尝试为特定月份生成一个

标签: python django csv django-views export-to-csv


【解决方案1】:

请阅读csv module documentation,尤其是writer object API

您会注意到 csv.writer 对象采用一个列表,其中包含表示它们在分隔行中的位置的元素。因此,要获得所需的输出,您需要像这样传递一个列表:

writer = csv.writer(response)
writer.writerow(['S.No', 'product_name', 'product_buyer'] + range(1, d) + ['total'])

这将为您提供所需的标题输出。

如果您只想填充行的某些部分,您可能想探索csv.DictWriter 类。干净多了。你会这样做:

writer = csv.DictWriter(response, 
                        ['S.No', 'product_name', 'product_buyer'] + range(1, d) + ['total'])

那么当你的写命令会这样:

for f in m:
    writer.writerow({'product_name': f.product_name, 'product_buyer': f.product_buyer})

【讨论】:

  • 感谢您的代码,这里我无法根据日期获取数据,例如 range(1,d) r 喜欢日期标题,取决于我需要根据该单元格提取数据..
  • 你能举个例子说明你正在尝试做什么吗?
  • 我在问题中添加了示例
猜你喜欢
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 2021-03-23
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多