赞
踩
目录
需要先安装xlwt模块
pip install -i https://pypi.douban.com/simple xlwt
- import xlwt
-
- # 创建一个Excel文件对象
- workbook = xlwt.Workbook()
-
- # 添加一个工作表
- worksheet = workbook.add_sheet('Sheet1')
-
- # 写入表头
- worksheet.write(0, 0, '姓名')
- worksheet.write(0, 1, '年龄')
- worksheet.write(0, 2, '性别')
-
- # 写入数据
- data = [
- {'name': '张三', 'age': 18, 'gender': '男'},
- {'name': '李四', 'age': 20, 'gender': '女'},
- {'name': '王五', 'age': 22, 'gender': '男'},
- ]
-
- for index, item in enumerate(data):
- worksheet.write(index+1, 0, item['name'])
- worksheet.write(index+1, 1, item['age'])
- worksheet.write(index+1, 2, item['gender'])
-
- # 保存Excel文件
- workbook.save('example.xlsx')
以下代码分为以下几个步骤:
xlwt.Workbook()
workbook.add_sheet('Sheet1')
worksheet.write(0, 0, '姓名')
write方法共三个参数:write(行坐标,列坐标,数据)
生成的excel表格内容如下:
所以依照上面的示例使用django读取数据库数据并写入到excel表格中
views.py
- from django.views.generic import View
- import xlwt
- class ExportExcel(View):
- def post(self, request):
- try:
- # 创建一个Excel文件对象
- workbook = xlwt.Workbook(encoding='utf-8')
- # 添加一个工作表
- worksheet = workbook.add_sheet('Sheet1')
- # 写入表头
- worksheet.write(0, 0, '序号')
- worksheet.write(0, 1, '所属学校')
- worksheet.write(0, 2, '学校代码')
- worksheet.write(0, 3, '课程名称')
- worksheet.write(0, 4, '课程编码')
- worksheet.write(0, 5, '课程类别')
- worksheet.write(0, 6, '课程专家')
- worksheet.write(0, 7, '院校性质')
-
- # 查询数据库
- lectures = ArtEducationLecture.objects.all()
-
- # 遍历读取数据并写入
- for index, lecture in enumerate(lectures):
- worksheet.write(index+1, 0, index+1)
- if lecture.colleges:
- worksheet.write(index + 1, 1, lecture.colleges.school_name)
- worksheet.write(index + 1, 2, lecture.colleges.username)
- worksheet.write(index + 1, 7, "艺术" if lecture.colleges.is_artmajor else "非艺术")
- if lecture.category:
- worksheet.write(index + 1, 5, lecture.category.name)
- worksheet.write(index + 1, 3, lecture.lecture_name)
- worksheet.write(index + 1, 4, lecture.YK_code)
- if lecture.expert:
- experts = lecture.expert.all()
- expert_list = [expert.name for expert in experts]
- expert = ','.join(expert_list)
- worksheet.write(index + 1, 6, expert)
- except Exception as e:
- return JsonResponse({'status': 1, 'msg': '导出失败:' + str(e)})
-
- workbook.save('2023课程汇总表.xlsx')
- return JsonResponse({'status': 0, 'msg': '导出成功'})
urls.py
- from django.views.decorators.csrf import csrf_exempt
-
- url("^export_excel/$", csrf_exempt(admin_views.ExportExcel.as_view())), # 导出优课信息
以上代码,先是使用xlwt.Workbook(encoding='utf-8')创建了表格对象,编码是utf-8,如果不指定可能在写入数据时报以下错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
接下来查询数据库表内容lectures = ArtEducationLecture.objects.all(),遍历读取字段内容并写入excel表格中
路由url使用csrf_exempt跳过csrf验证
生成的表格内容如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。