在Django中实现DataFrame导出为CSV的下载按钮功能
问题描述
我是Django新手,目前已在views.py中通过已连接的MSSQL数据库获取了DataFrame(df),相关代码如下:
Views.py
def CaseTest(request): # 修正原代码缺失的冒号 dfa_query = """ Select * from database """ dfa = pandas.read_sql_query(dfa_query, connection) dfa_html = dfa.to_html(index=False, table_id='dbtable') # 修正原代码引号闭合错误 return render(request, 'CaseTest.html')
CaseTest.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CaseTest</title> </head> <body> {% load site_extra %} <h2> CaseTest DF </h2> <div style="height: 500px; overflow: auto;"> {{ dfa_html | safe }} <!-- 修正原代码变量名错误 --> </div> </body> </html>
我希望在HTML页面中添加一个按钮,用户点击该按钮即可下载上述DataFrame,请问该如何实现?
实现方案
以下提供两种实用的实现方式,可根据代码结构需求选择:
方式一:同一视图处理页面展示与下载请求
直接在现有视图中添加判断逻辑,区分页面渲染和下载请求:
1. 修改views.py
import pandas as pd from django.http import HttpResponse def CaseTest(request): dfa_query = """ Select * from database """ dfa = pd.read_sql_query(dfa_query, connection) dfa_html = dfa.to_html(index=False, table_id='dbtable') # 判断是否为下载请求 if request.GET.get('download') == 'true': # 生成Excel文件(推荐,格式友好) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="case_data.xlsx"' dfa.to_excel(response, index=False) return response # 若需下载CSV,替换上述三行为: # response = HttpResponse(content_type='text/csv') # response['Content-Disposition'] = 'attachment; filename="case_data.csv"' # dfa.to_csv(response, index=False, encoding='utf-8-sig') # return response return render(request, 'CaseTest.html', {'dfa_html': dfa_html})
2. 修改CaseTest.html添加下载按钮
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CaseTest</title> </head> <body> {% load site_extra %} <h2> CaseTest DF </h2> <!-- 添加下载按钮 --> <button onclick="window.location.href='?download=true'">下载数据</button> <div style="height: 500px; overflow: auto;"> {{ dfa_html | safe }} </div> </body> </html>
方式二:单独创建下载视图(代码结构更清晰)
将页面展示与下载逻辑分离,适合复杂场景:
1. 修改views.py添加下载视图
import pandas as pd from django.http import HttpResponse def CaseTest(request): dfa_query = """ Select * from database """ dfa = pd.read_sql_query(dfa_query, connection) dfa_html = dfa.to_html(index=False, table_id='dbtable') return render(request, 'CaseTest.html', {'dfa_html': dfa_html}) def download_case_data(request): dfa_query = """ Select * from database """ dfa = pd.read_sql_query(dfa_query, connection) # 生成Excel文件 response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="case_data.xlsx"' dfa.to_excel(response, index=False) return response # CSV版本替换: # response = HttpResponse(content_type='text/csv') # response['Content-Disposition'] = 'attachment; filename="case_data.csv"' # dfa.to_csv(response, index=False, encoding='utf-8-sig') # return response
2. 在urls.py中添加下载路由
from django.urls import path from . import views urlpatterns = [ path('case-test/', views.CaseTest, name='case-test'), path('download-case-data/', views.download_case_data, name='download-case-data'), ]
3. 修改CaseTest.html中的按钮链接
<button onclick="window.location.href='{% url 'download-case-data' %}'">下载数据</button>
注意事项
- 若使用Excel导出,需提前安装依赖库:
pip install openpyxl - CSV导出时添加
encoding='utf-8-sig'可避免中文乱码问题 - 已修正原代码中的变量名、语法错误,确保页面正常渲染表格
内容的提问来源于stack exchange,提问作者xlxdxf
相关产品推荐
相关产品推荐

