[英]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.