django excel xlwt

前端 未结 6 654
醉梦人生
醉梦人生 2020-12-02 08:15

On a django site, I want to generate an excel file based on some data in the database.

I\'m thinking of using xlwt, but it only has a method to save the data to a fi

6条回答
  •  一整个雨季
    2020-12-02 08:37

    neat package! i didn't know about this

    According to the doc, the save(filename_or_stream) method takes either a filename to save on, or a file-like stream to write on.

    And a Django response object happens to be a file-like stream! so just do xls.save(response). Look the Django docs about generating PDFs with ReportLab to see a similar situation.

    edit: (adapted from ShawnMilo's comment):

    def xls_to_response(xls, fname):
        response = HttpResponse(mimetype="application/ms-excel")
        response['Content-Disposition'] = 'attachment; filename=%s' % fname
        xls.save(response)
        return response
    

    then, from your view function, just create the xls object and finish with

    return xls_to_response(xls,'foo.xls')
    

提交回复
热议问题