【发布时间】:2021-05-09 12:49:28
【问题描述】:
def export_as_xls(self, request, queryset): opts = self.model._meta file_name = unidecode(opts.verbose_name) sql_query = '''SELECT COUNT(id) AS No_Of_Report, vendor, country_code, SUM(new_code)*100/SUM(sent) AS 'failure_rate', SUM(case when new_code =0 then 1 ELSE 0 end)*100/sum(sent) AS 'success_rate' FROM sms_statistics WHERE FROM_UNIXTIME(date) >= curdate() - interval 30 day GROUP BY vendor, country_code ORDER BY vendor DESC;'''
这是我用来调用 mysql 架构中数据的 mysql 查询
field_names = ('No of report', 'Vendor', 'Country Code', 'Failure Rate', 'Success Rate') wb = Workbook() ws = wb.active ws.append(ExportExcelAction.generate_header(self, self.model, field_names)) with connection.cursor() as cursor: cursor.execute(sql_query) objects = list(cursor.fetchall()) for row in cursor.fetchall(): objects = list(row) ws.append(objects) print(ws.append(row)) ws = style_output_file(ws)我认为问题出在无法导出到 Excel 中。我没有使用正确的方法从 action.py 导出文件
响应 = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'附件;文件名={文件名}.xlsx' wb.save(响应) 返回响应 export_as_xls.short_description = "过去 30 天的报告" export_as_xls.acts_on_all = True
块引用
我相信这部分没问题,因为我尝试导出一个空文件并将其作为 expexted 工作
【问题讨论】: