django csv标题和行格式问题

发布于 2024-10-21 05:37:05 字数 1882 浏览 9 评论 0原文

我正在尝试创建 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

I am trying to create csv download ,but result download gives me in different format

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

output of above code :

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


mgm | x_name
wge | y_name

I am looking out put like this

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

can you please help me with above csv download ?
if possible can you please tell me how to sum up all the individual user total at end?

Example :

we have selling table in that every day seller info will be inserted

table data looks like

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

I have created a table where it displays below format and i am trying to create csv download

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月亮邮递员 2024-10-28 05:37:05

请阅读 csv 模块文档,特别是 编写器对象 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})

Please read the csv module documentation, particularly the writer object API.

You'll notice that the csv.writer object takes a list with elements representing their position in your delimited line. So to get the desired output, you would need to pass in a list like so:

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

This will give you your desired header output.

You might want to explore the csv.DictWriter class if you want to only populate some parts of the row. It's much cleaner. This is how you would do it:

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

Then when your write command would follow as so:

for f in m:
    writer.writerow({'product_name': f.product_name, 'product_buyer': f.product_buyer})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文