Excel文件导出前端页面下载

django

from openpyxl import Workbook
from io import BytesIO

class ExportData(View):
    def post(self, request):
        response = HttpResponse(content_type = 'application/octet-stream')
        try:
            response['Content-Disposition'] = 'attachment;filename={}.xlsx'.format('excel_data')
            response['Attachment-Name'] = '{}.xlsx'.format('excel_data')

            objDataList = models.Users.objects.filter().order_by('id')

            wb = Workbook()
            sheet = wb.create_sheet('工作簿名称', 0)
            for i, key in enumerate(['Username', 'Password', '创建时间', '最近登录时间'], 1):
                sheet.cell(1, i, key)

            for item in objDataList:
                sheet.append([
                    item.username,
                    item.password,
                    item.created_date,
                    item.last_login_date
                ])
        
            outputStream = BytesIO()
            wb.save(outputStream)
            outputStream.seek(0)
            response.write(outputStream.getvalue())

        except Exception as error:
            print(error)
            response.status_code = 500
        
        return response

前端

// 导出全部数据
onExportData () {
    this.isExport = true
    this.$http({
        url: this.config.exportRecordUrl,
        method: 'post',
        responseType: 'blob'
    }).then(resp => {
        if (resp.status === 200) {
            let blob = new Blob([resp.data])
            let link = document.createElement('a')
            link.download = '用户表.xlsx'
            link.href = URL.createObjectURL(blob)
            link.click()
            URL.revokeObjectURL(link.href)
        } else {
            this.$message.error('导出失败')
        }
    }).finally(() => {
        this.isExport = false
    })
},

或者使用axios-stream

https://www.npmjs.com/package/axios-stream

你可能感兴趣的:(Excel文件导出前端页面下载)