使用Django和Pandas将Excel文件返回给用户可以通过以下步骤实现:
pip install django pandas
import pandas as pd
from django.http import HttpResponse
def excel_view(request):
# 读取Excel文件数据
data = pd.read_excel('path/to/excel_file.xlsx')
# 将数据导出为Excel文件
output = io.BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
data.to_excel(writer, index=False, sheet_name='Sheet1')
writer.save()
output.seek(0)
# 构建HTTP响应,将Excel文件返回给用户
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="excel_file.xlsx"'
response.write(output.getvalue())
return response
from django.urls import path
from . import views
urlpatterns = [
path('download-excel/', views.excel_view, name='excel_view'),
]
http://localhost:8000/download-excel/
。这样,用户就可以通过访问指定URL路径来下载由Django和Pandas生成的Excel文件了。
注意:以上代码仅为示例,实际应用中可能需要根据具体需求进行适当的修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云