장고 엑셀로 데이터 받기

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