"장고 엑셀로 데이터 받기"의 두 판 사이의 차이
둘러보기로 가기
검색하러 가기
(새 문서: == 개요 == 장고로 데이터를 가공하여 엑셀로 다운받는 기능을 구현하기 위한 기능을 설명하기 위한 문서이다. 엑셀 데이터 생성에 대해선...) |
(→뷰 작성) |
||
(같은 사용자의 중간 판 하나는 보이지 않습니다) | |||
13번째 줄: | 13번째 줄: | ||
response["Content-Disposition"] = 'attachment; filename=' + '파일명' + '.xls' | response["Content-Disposition"] = 'attachment; filename=' + '파일명' + '.xls' | ||
+ | # 알아서 데이터 입력. | ||
wb = xlwt.Workbook(encoding='utf-8') # 인코딩 | wb = xlwt.Workbook(encoding='utf-8') # 인코딩 | ||
ws = wb.add_sheet('시트이름') | ws = wb.add_sheet('시트이름') | ||
20번째 줄: | 21번째 줄: | ||
return response | return response | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | === 더 나아가 === | ||
+ | 위 방식대로 하면 xls로 다운받아지고 에러메시지가 계속해 발생하고 파일명 설정이 먹히질 않는다. 아래 방식은 df를 엑셀로 다운받게 도와주는 함수를 모듈화 한 것인데, 참고하길.<syntaxhighlight lang="python"> | ||
+ | from django.http import HttpResponse | ||
+ | |||
+ | def df_to_excel_download(df, filename='지난지나니 다운'): | ||
+ | response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') | ||
+ | from django.utils.encoding import escape_uri_path # 파일명을 '다운로드'가 아닌 지정한 형태로 가져가기 위해 필요한 것. | ||
+ | filename = f"{filename}.xlsx" | ||
+ | response['Content-Disposition'] = f'attachment; filename="{escape_uri_path(filename)}"' | ||
+ | df.to_excel(response, index=False) | ||
+ | return response | ||
</syntaxhighlight> | </syntaxhighlight> | ||
[[분류:장고 엑셀]] | [[분류:장고 엑셀]] |
2023년 10월 25일 (수) 12:11 기준 최신판
1 개요[편집 | 원본 편집]
장고로 데이터를 가공하여 엑셀로 다운받는 기능을 구현하기 위한 기능을 설명하기 위한 문서이다.
엑셀 데이터 생성에 대해선 분류:엑셀 헨들링 문서를 참고하자.
2 뷰 작성[편집 | 원본 편집]
from django.http import HttpResponse
import 취향에 맞는 엑셀 헨들러
def excel_download(request):
response = HttpResponse(content_type="application/vnd.ms-excel")
response["Content-Disposition"] = 'attachment; filename=' + '파일명' + '.xls'
# 알아서 데이터 입력.
wb = xlwt.Workbook(encoding='utf-8') # 인코딩
ws = wb.add_sheet('시트이름')
#.... 알아서 데이터 입력
wb.save(response) # response에 저장.
return response
2.1 더 나아가[편집 | 원본 편집]
위 방식대로 하면 xls로 다운받아지고 에러메시지가 계속해 발생하고 파일명 설정이 먹히질 않는다. 아래 방식은 df를 엑셀로 다운받게 도와주는 함수를 모듈화 한 것인데, 참고하길.
from django.http import HttpResponse
def df_to_excel_download(df, filename='지난지나니 다운'):
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
from django.utils.encoding import escape_uri_path # 파일명을 '다운로드'가 아닌 지정한 형태로 가져가기 위해 필요한 것.
filename = f"{filename}.xlsx"
response['Content-Disposition'] = f'attachment; filename="{escape_uri_path(filename)}"'
df.to_excel(response, index=False)
return response