Excelのダウンロード(zipファイル)

7881 ワード

    def download_excel(self, request, queryset):
        # order_set = queryset.select_related('status', 'user', 'address').filter(status__id__range=(2, 3))
        order_set = queryset.select_related('status', 'user', 'address').filter(status__id=3)
        if not order_set:
            msg = "[상품 준비 중]인 주문이 존재하지 않습니다."
            response = HttpResponse(msg, status=400)
            return response

        response = HttpResponse()
        response['Content-Type'] = "application/x-zip-compressed"
        response['Content-Disposition'] = 'attachment; filename="cnplus_download.zip"'

        # write zip to response
        z = zipfile.ZipFile(response, 'w')
        cnt = 1
        for order in order_set:
            now = datetime.datetime.now()
            file_name = now.strftime("%Y%m%d%H%m%s") + "_" + str(cnt) + ".xlsx"
            cnt += 1
            excel = Workbook()
            excel_writer = excel.active

            # code for writing excel file
            nav_bar = [
                "고객 주문번호",
                "받는분성명",
                "받는분전화번호",
                "받는분기타연락처",
                "받는분주소(전체, 분할)",
                "배송메세지1",
                "품목명",
                "내품코드"
            ]
            excel_writer.append(nav_bar)

            # 주문번호
            order_number = order.order_number
            # 주문명
            order_name = order.order_name
            # 받는분 전화번호 
            phone_number = order.address.phone_number
            # 수령인 
            recipient = order.address.recipient
            # 주소
            address = order.address.name
            data_row = [order_number, recipient, phone_number, "", address, "", order_name, ""]
            excel_writer.append(data_row)
            excel.save(file_name)
            z.write(file_name)
        z.close()
        return response

    download_excel.short_description = "대한통운 양식 다운로드"