Django implements reading data export to generate excel form

Table of contents

1. Simple example:

1. Create a file object:

2. Add a worksheet:

3. Write data:

2. Practice the truth


You need to install the xlwt module first

pip install -i https://pypi.douban.com/simple xlwt

1. Simple example:

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')

The following code is divided into the following steps:

1. Create a file object:

xlwt.Workbook()

2. Add a worksheet:

workbook.add_sheet('Sheet1')

3. Write data:

worksheet.write(0, 0, '姓名') 

The write method has three parameters: write(row coordinates, column coordinates, data)

The contents of the generated excel table are as follows:

2. Practice the truth

So according to the above example, use django to read the database data and write it into the excel table

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())),  # 导出优课信息

The above code first uses xlwt.Workbook(encoding='utf-8') to create a table object, and the encoding is utf-8. If it is not specified, the following error may be reported when writing data:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

Next, query the content of the database table lectures = ArtEducationLecture.objects.all() , traverse and read the field content and write it into the excel table

Routing url uses csrf_exempt to skip csrf verification

The generated table content is as follows:

Guess you like

Origin blog.csdn.net/qq_37140721/article/details/131125378
Recommended