Skip to content

想请教下您,自定义的excel数据应该如何使用平台统一的Response类响应呢? #85

@casuallyone

Description

@casuallyone

目前只会使用django原生形式,比较繁琐...

from django.http import HttpResponse
from django.utils.encoding import escape_uri_path
class MaterialViewSet(BaseModelSet):
    """Material""" 

    queryset = Material.objects.all()
    serializer_class = MaterialSerializer
    filterset_class = MaterialViewSetFilter

    @action(methods=['get'], detail=False, url_path='export')
    def _process(self, *args, **kwargs):
        pass
    def export(self, request):
        """导出查询数据"""
        result = self._process(request)
        
        df = pd.DataFrame.from_dict(result, orient='index')
        
        excel_file = BytesIO()
        with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:
            df.to_excel(writer, index=True, sheet_name='XXXX')
        excel_file.seek(0)
        response = HttpResponse(
            content=excel_file.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        )

        file_name = "XXXX"
        response['Content-Disposition'] = f"attachment;filename={escape_uri_path(file_name)}.xlsx"
        response['Access-Control-Expose-Headers'] = "Content-Disposition"

        response.write(excel_file.getvalue())
        return response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions