|
|
@@ -1,4 +1,4 @@
|
|
|
-## 报表
|
|
|
+## 制作报表
|
|
|
|
|
|
### 导出Excel报表
|
|
|
|
|
|
@@ -52,6 +52,26 @@ urlpatterns = [
|
|
|
]
|
|
|
```
|
|
|
|
|
|
+### 导出PDF报表
|
|
|
+
|
|
|
+在Django项目中,如果需要导出PDF报表,可以借助三方库reportlab来生成PDF文件的内容,再将文件的二进制数据输出给浏览器并指定MIME类型为`application/pdf`,具体的代码如下所示。
|
|
|
+
|
|
|
+```Python
|
|
|
+def export_pdf(request: HttpRequest) -> HttpResponse:
|
|
|
+ buffer = io.BytesIO()
|
|
|
+ pdf = canvas.Canvas(buffer)
|
|
|
+ pdf.setFont("Helvetica", 80)
|
|
|
+ pdf.setFillColorRGB(0.2, 0.5, 0.3)
|
|
|
+ pdf.drawString(100, 550, 'hello, world!')
|
|
|
+ pdf.showPage()
|
|
|
+ pdf.save()
|
|
|
+ resp = HttpResponse(buffer.getvalue(), content_type='application/pdf')
|
|
|
+ resp['content-disposition'] = 'inline; filename="demo.pdf"'
|
|
|
+ return resp
|
|
|
+```
|
|
|
+
|
|
|
+关于如何用reportlab定制PDF报表的内容,可以参考reportlab的[官方文档](https://www.reportlab.com/docs/reportlab-userguide.pdf)。
|
|
|
+
|
|
|
### 生成前端统计图表
|
|
|
|
|
|
如果项目中需要生成前端统计图表,可以使用百度的[ECharts](<https://echarts.baidu.com/>)。具体的做法是后端通过提供数据接口返回统计图表所需的数据,前端使用ECharts来渲染出柱状图、折线图、饼图、散点图等图表。例如我们要生成一个统计所有老师好评数和差评数的报表,可以按照下面的方式来做。
|
|
|
@@ -62,7 +82,6 @@ def get_teachers_data(request):
|
|
|
names = [teacher.name for teacher in queryset]
|
|
|
good_counts = [teacher.good_count for teacher in queryset]
|
|
|
bad_counts = [teacher.bad_count for teacher in queryset]
|
|
|
- # 返回JSON格式的数据
|
|
|
return JsonResponse({'names': names, 'good': good_counts, 'bad': bad_counts})
|
|
|
```
|
|
|
|