How can Django generate an Excel spreadsheet?

Django itself does not offer the ability to generate Excel spreadsheets, but you can achieve this functionality by using a third-party library. Below is a simple example demonstrating how to use the openpyxl library in Django to generate Excel spreadsheets.

  1. Firstly, install the openpyxl library.
pip install openpyxl
  1. Write the code for generating an Excel spreadsheet in the views.py file of Django.
from django.http import HttpResponse
from openpyxl import Workbook

def generate_excel(request):
    # 创建一个新的Excel工作表
    wb = Workbook()
    ws = wb.active

    # 在工作表中写入数据
    ws['A1'] = 'Name'
    ws['B1'] = 'Age'

    ws['A2'] = 'Alice'
    ws['B2'] = 25

    ws['A3'] = 'Bob'
    ws['B3'] = 30

    # 保存Excel文件
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="example.xlsx"'
    wb.save(response)

    return response
  1. 在urls.py文件中添加URL映射:
from django.urls import path
from .views import generate_excel

urlpatterns = [
    path('generate_excel/', generate_excel, name='generate_excel'),
]
  1. Simply access the URL in your browser to download the Excel file generated.

Please note that the code above is just a simple example. You can customize it to generate Excel sheets with different formats and content based on your requirements. Additionally, you may also consider using other libraries like pandas to create Excel sheets.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds