【发布时间】:2010-12-28 05:00:21
【问题描述】:
我是 django 和 python 的新手。在这个任务中需要一些指导。
案例:当用户点击表单上的提交按钮时,它应该显示成功页面和一个可以下载结果的链接。结果在excel文件中。我可以使用 xlwt 模块创建输出到 excel 文件并单独显示成功页面,但不能同时显示两者。
我有什么: 我正在使用 python 2.6 在 Windows XP 上运行 django1.1.1。有类似的问题被问到 但无法使其工作。
我的成功 page.html 有这一行
<a href="../static/example.xls">Download CSV File</a>
urls.py:
url(r'^static/(?P<path>.*)$', send_file),
views.py:
def send_file(request):
import os, tempfile, zipfile
from django.core.servers.basehttp import FileWrapper
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""
filename = "C:/example.xls" # Select your file here.
wrapper = FileWrapper(file(filename),"rb")
response = HttpResponse(wrapper, content_type='text/plain')
#response['Content-Length'] = os.path.getsize(filename)
return response
当我点击链接时,它给出了路径错误
send_file() got an unexpected keyword argument 'path'
Request Method: GET
Request URL: localhost:8000/webinput/static/example.xls
Exception Type: TypeError
Exception Value:
send_file() got an unexpected keyword argument 'path'
顺便说一句,example.xls 位于 C:/example.xls 和静态文件夹中
结构:
- 网络数据库
- 静态
- example.xls
- 网页输入
- urls.py
- views.py
- models.py
- 静态
我也有这两个模块。如果我使用 backup_to_csv 它工作正常,但它直接下载而没有链接。当我已经有文件时如何做同样的事情。如果有其他方式我不必存储文件,那也很好。
def xls_to_response(xls, fname):
response = HttpResponse(mimetype="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename=%s' % fname
xls.save(response)
return response
def backup_to_csv(request,row):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename="backup.csv"'
writer = csv.writer(response, dialect='excel')
#code for writing csv file go here...
for i in row:
writer.writerow(i)
return response
【问题讨论】:
标签: django file csv download xls