django實現將後臺資料excel檔案形式匯出

龙岩龙發表於2024-03-15

檢視函式export_persons

引入匯出excle相關庫

import xlwt

def export_persons(request):
# 獲取資料庫中的所有Project物件
persons = m1.Project.objects.all()

# 建立Excel檔案
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = book.add_sheet('Sheet', cell_overwrite_ok=True)

# 寫入表頭
sheet.write(0, 0, '專案ID')
sheet.write(0, 1, '題目')
sheet.write(0, 2, '開始時間')
sheet.write(0, 3, '結束時間')
sheet.write(0, 4, '建立人')


# 寫入資料
row_num = 1
for person in persons:
    sheet.write(row_num, 0, person.id)
    sheet.write(row_num, 1, person.title)
    sheet.write(row_num, 2, person.start_time)
    sheet.write(row_num, 3, person.end_time)
    sheet.write(row_num, 4, person.create_person_id)
    row_num += 1

# 儲存檔案並返回HttpResponse物件
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="persons.xls"'
book.save(response)
return response

相關文章