如果該文件是靜態(即不爲此請求專門產生的),你不應該通過Django的服務反正它。你應該配置一些路徑(比如/ static /)供你的web服務器使用,並保存所有的django開銷。
如果該文件是動態,有2個選項:
- 在內存中創建它,並從Django的服務於它。
- 在磁盤上創建它,並返回一個HttpResponseRedirect給它,以便您的Web服務器自行處理下載(如果文件非常大,則應使用此選項)。
至於動態服務它,我一直在使用下面的代碼(這是ExcelResponse的簡化版本)
import StringIO
from django.db.models.query import ValuesQuerySet, QuerySet
class CSVResponse(HttpResponse):
def __init__(self, data, output_name='data', headers=None, encoding='utf8'):
# Make sure we've got the right type of data to work with
valid_data = False
if isinstance(data, ValuesQuerySet):
data = list(data)
elif isinstance(data, QuerySet):
data = list(data.values())
if hasattr(data, '__getitem__'):
if isinstance(data[0], dict):
if headers is None:
headers = data[0].keys()
data = [[row[col] for col in headers] for row in data]
data.insert(0, headers)
if hasattr(data[0], '__getitem__'):
valid_data = True
assert valid_data is True, "CSVResponse requires a sequence of sequences"
output = StringIO.StringIO()
for row in data:
out_row = []
for value in row:
if not isinstance(value, basestring):
value = unicode(value)
value = value.encode(encoding)
out_row.append(value.replace('"', '""'))
output.write('"%s"\n' %
'","'.join(out_row))
mimetype = 'text/csv'
file_ext = 'csv'
output.seek(0)
super(CSVResponse, self).__init__(content=output.getvalue(),
mimetype=mimetype)
self['Content-Disposition'] = 'attachment;filename="%s.%s"' % \
(output_name.replace('"', '\"'), file_ext)
要使用它,只需用迴歸CSVResponse(...)傳球在列表列表中,列表(具有相同的鍵),查詢集,值查詢集
試過了,依然不起作用。我可以在FireBug中看到響應和標題,但我沒有看到對話框。 – spyder 2010-03-17 19:39:36
試試我目前的編輯。 – Cerin 2010-03-18 17:30:01
我試過但沒有工作。請看我的回覆,我發現這個問題與django無關。謝謝 – spyder 2010-03-18 17:45:36