[英]csv.writer writing each character of word
我正在嘗試從模型 Locations 中導出名稱列表。 Locations 有幾個包含名稱列表的對象,例如:
['New York', 'Ohio', California'] ['New York', 'Chicago', California'] ['Miami', 'Ohio', California']
導出函數如下:
def export(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['Location']) #header
for launch in Location.objects.all().values_list('L_name'):
export_data = zip_longest(*launch, fillvalue='')
writer.writerows(export_data)
response['Content_Disposition'] = 'attatchment';
return response
Writerow 正在迭代每個名稱的字符,生成一列字符而不是名稱。 相反,我希望每個 Location 對象的每個名稱都位於同一列中的自己行中。 上面的示例將導致九行。
關於如何實現這一目標的任何想法?
感謝您提供任何意見。
這是因為writerows
需要一個可迭代的行。 這些行中的每一行都有一個可迭代的列。 但是這里export_data
是一個可迭代的。 此外,您不需要使用zip_longest
,您可以使用:
def export(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['Location']) #header
writer.writerows(Location.objects.values_list('L_name'))
response['Content_Disposition'] = 'attachment';
return response
或者如果L_name
是ArrayField
等,您可以使用以下方法展開它:
def export(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['Location']) #header
writer.writerows((x,) for xs in Location.objects.values_list('L_name')for x in xs)
response['Content_Disposition'] = 'attachment';
return response
我最終這樣做了:
def export(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['Base']) #header
for launch in Location.objects.all().values_list('L_name'):
list_launch = list(launch)
full_str = ' '.join([str(elem) for elem in list_launch])
str_split = ([full_str.split(",")])
export_data = zip_longest(*str_split, fillvalue='')
writer.writerows(export_data)
response['Content_Disposition'] = 'attatchment';
return response`
將列表轉換為字符串,在逗號處拆分字符串,然后使用行 zip_longest(*str_split, fillvalue='') 在其自己的行上垂直輸出每個名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.