admin.py 文件源码

python
阅读 19 收藏 0 点赞 0 评论 0

项目:Django-Web-Development-with-Python 作者: PacktPublishing 项目源码 文件源码
def export_xls(modeladmin, request, queryset):
    response = HttpResponse(content_type="application/ms-excel")
    response["Content-Disposition"] = "attachment; filename=products.xls"
    wb = xlwt.Workbook(encoding="utf-8")
    ws = wb.add_sheet("Products")

    row_num = 0

    columns = [
        ("ID", 2000),
        ("Title", 6000),
        ("Description", 8000),
        ("Price (€)", 3000),
        ("Preview", 10000),
    ]

    header_style = xlwt.XFStyle()
    header_style.font.bold = True

    for col_num, (item, width) in enumerate(columns):
        ws.write(row_num, col_num, item, header_style)
        # set column width
        ws.col(col_num).width = width

    text_style = xlwt.XFStyle()
    text_style.alignment.wrap = 1

    price_style = xlwt.XFStyle()
    price_style.num_format_str = "0.00"

    styles = [text_style, text_style, text_style, price_style, text_style]

    for obj in queryset.order_by("pk"):
        row_num += 1
        project_photos = obj.productphoto_set.all()[:1]
        url = ""
        if project_photos:
            url = "http://{0}{1}".format(
                request.META['HTTP_HOST'],
                project_photos[0].photo.url,
            )
        row = [
            obj.pk,
            obj.title,
            obj.description,
            obj.price,
            url,
        ]
        for col_num, item in enumerate(row):
            ws.write(row_num, col_num, item, styles[col_num])

    wb.save(response)
    return response
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号