35

django サイトで、データベース内のデータに基づいて Excel ファイルを生成したいと考えています。

xlwtの使用を考えていますが、データをファイルに保存する方法しかありません。ファイルを HttpResponse オブジェクトに取得するにはどうすればよいですか? それとも、より良いライブラリを知っていますか?

このスニペットも見つけましたが、必要な機能がありません。必要なのは、xlwt オブジェクトから応答オブジェクトへのストリームを取得する方法だけです (一時ファイルに書き込む必要はありません)。

4

6 に答える 6

56

きちんとしたパッケージ!私はこれについて知りませんでした

ドキュメントによると、このsave(filename_or_stream)メソッドは、ファイル名を使用して保存するか、ファイルのようなストリームを使用して書き込みを行います。

そして、Djangoレスポンスオブジェクトはたまたまファイルのようなストリームです!だから、そうするだけですxls.save(response)。同様の状況を確認するには、ReportLabを使用したPDFの生成に関するDjangoドキュメントを参照してください。

編集: (ShawnMiloのコメントから採用):

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

次に、ビュー関数から、xlsオブジェクトを作成して終了します。

return xls_to_response(xls,'foo.xls')
于 2009-05-19T15:09:44.250 に答える
6

***更新: django-excel-templates はメンテナンスされなくなりました。代わりに Marmir http://brianray.github.com/mm/を試してください。

これを入力する時点ではまだ開発中ですが、http://code.google.com/p/django-excel-templates/ Django Excel テンプレート プロジェクトは、あなたの要求を実行することを目的としています。

具体的には、テストを見てください。以下は単純なケースです。

#
from django_excel_templates import *
from django_excel_templates.color_converter import *
from models import *
from django.http import HttpResponse

def xls_simple(request):

    ## Simple ##
    testobj = Book.objects.all()

    formatter = ExcelFormatter()
    simpleStyle = ExcelStyle(vert=2,wrap=1)
    formatter.addBodyStyle(simpleStyle)
    formatter.setWidth('name,category,publish_date,bought_on',3000)
    formatter.setWidth('price',600)
    formatter.setWidth('ebook',1200)
    formatter.setWidth('about',20000)

    simple_report = ExcelReport()
    simple_report.addSheet("TestSimple")
    filter = ExcelFilter(order='name,category,publish_date,about,bought_on,price,ebook')
    simple_report.addQuerySet(testobj,REPORT_HORZ,formatter, filter)

    response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
    return response
于 2010-01-28T06:05:15.223 に答える
2

XLS ファイルは、ファイルのようなStringIOオブジェクトに保存できます。

getvalue()応答でStringIO オブジェクトを返すことができます。ダウンロード可能なスプレッドシートとしてマークするヘッダーを必ず追加してください。

于 2009-05-19T19:17:54.917 に答える
2

クエリセットをダウンロード可能な Excel シートに変換するという関数に適合する huDjangoを確認することをお勧めします。serializers.queryset_to_xls()

于 2009-09-01T13:56:18.617 に答える
1

https://bitbucket.org/kmike/django-excel-responseを使用

于 2011-10-06T13:36:50.723 に答える
0

データ結果に数式や正確な表示スタイルが必要ない場合は、いつでもCSVを使用できます。スプレッドシートプログラムはそれを直接読み取ります。CSVを生成するWebアプリを見たこともありますが、Excelで確実に開くために.XSLという名前を付けています。

于 2009-05-19T15:15:40.337 に答える