【发布时间】:2021-12-18 10:30:28
【问题描述】:
我正在使用此功能从数据库中导出数据:
def export_packing_xls(request):
response = HttpResponse(content_type='application/ms-excel')
file_name = "packing_list_"+str(datetime.now().date())+".xls"
response['Content-Disposition'] = 'attachment; filename="'+ file_name +'"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Packing List')
date1 = request.GET.get('exportStartDate')
date2 = request.GET.get('exportEndDate')
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
columns = ['Ref Number', 'Description of Goods','QTY','Gross WT',]
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
rows = Booking.objects.filter(created_at__range =[date1, date2]).values_list('booking_reference', 'product_list', 'gross_weight',)
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
print(row[col_num][1][:4])
wb.save(response)
return response
Ref Number Description of Goods QTY Gross WT
AWBO114 [{"id":1,"Name":"T shirt","Quantity":"10","Weight":"2","WeightTypes":"KG","TotalWeight":"20","CustomsCharge":"20.0","Discount":"12","Subtotal":"188"}] 12 22
AWBO117 [{"id":1,"Name":"T shirt","Quantity":"15","Weight":"45","WeightTypes":"KG","TotalWeight":"675","CustomsCharge":"20.0","Discount":"45","Subtotal":"255"}] 45 455
AWBO118 [{"id":1,"Name":"Fan","Quantity":"12","Weight":"12","WeightTypes":"KG","TotalWeight":"144","CustomsCharge":"100.0","Discount":"12"},{"id":2,"Name":"T shirt","Quantity":"22","Weight":"5","WeightTypes":"KG","TotalWeight":"110","CustomsCharge":"20.0","Discount":""}] 15 15
AWBO121 [{"id":1,"Name":"T shirt","Quantity":"12","Weight":"12","WeightTypes":"KG","TotalWeight":"144","CustomsCharge":"20.0","Discount":"12","Subtotal":"228"}] 0 20
AWBO122 [{"id":1,"Name":"T shirt","Quantity":"12","Weight":"12","WeightTypes":"KG","TotalWeight":"144","CustomsCharge":"20.0","Discount":"12","Subtotal":"228"}] 12 12
如何在 Excel 文件中列出我的 JSON 数据?
如果你有什么想知道的,请在评论区告诉我。 谢谢。
【问题讨论】:
-
你试过
write_merge吗? stackoverflow.com/questions/19672760/… -
您需要遍历第 2 列的 json,以便您可以浏览详细信息
-
@Walucas 我如何迭代 Json 数据?我尝试使用
row[col_num]['Name']这个命令,但是如果我使用row[col_num][0]这个命令 'float' 对象不可下标,它的 字符串索引必须是整数请问? -
@JoseAntonioCastroCastro 是的,我已经看到了,但我无法从 Json 列表中获得价值。
-
@MdAzharulIslamSumon 我将其添加为答案