Tích hợp tính năng xuất file Excel trong Django

Sử dụng thư viện xlsxwriter của Python để tạo file Excel. Lưu ý rằng thư viện này chỉ hỗ trợ tạo mới file Excel mà không hỗ trợ đọc hoặc sửa đổi, đồng thời không hỗ trợ định dạng XLS.

  1. Cấu hình URL (urls.py)
from django.contrib import admin
from django.urls import path, include
from web import views

urlpatterns = [
    path('xuat-excel/', views.xuat_excel),
    path('dang-nhap/', views.dang_nhap)
]
  1. Xử lý view (views.py)
import os
from django.conf import settings
from django.http import FileResponse
from xlsxwriter import Workbook
from .models import NguoiDung

def xuat_excel(request):
    duong_dan_goc = settings.BASE_DIR
    ten_file_dich = os.path.join(duong_dan_goc, 'tai_lieu', 'danh_sach.xlsx')
    
    wb = Workbook(ten_file_dich)
    ws = wb.add_worksheet("NhanVien")

    dong = 0
    cot = ["STT", "HoTen", "Tuoi", "MatKhau"]
    for i in range(len(cot)):
        ws.write(dong, i, cot[i])

    du_lieu = NguoiDung.objects.values_list('id', 'ten_dang_nhap', 'tuoi', 'mat_khau')
    for hang in du_lieu:
        dong += 1
        hang = list(hang)
        for i in range(len(hang)):
            ws.write(dong, 0, hang[0])
            ws.write(dong, 1, hang[1])
            ws.write(dong, 2, hang[2])
            ws.write(dong, 3, hang[3])
    wb.close()
    
    file_excel = open(ten_file_dich, 'rb')
    phan_hoi = FileResponse(file_excel)
    phan_hoi["Content-Type"] = 'application/octet-stream'
    phan_hoi['Content-Disposition'] = 'attachment;filename="{0}"'.format('danh_sach.xlsx')
    return phan_hoi

def dang_nhap(request):
    return render(request, 'dang_nhap.html')
  1. Template HTML (dang_nhap.html)
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Xuất Excel</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
</head>
<body>
<h1>Xin chào</h1>
    <button id="nut_xuat">Xuất file Excel</button>
    
    <!-- Phương pháp 1: Sử dụng thẻ a -->
    <div>
        <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" title="Xuất báo cáo" href="/xuat-excel/">Xuất báo cáo</a>
    </div>
    
    <script type="text/javascript">
        // Phương pháp 2: Sử dụng AJAX
        $('#nut_xuat').click(function () {
            $.ajax({
                url: 'xuat-excel/',
                type: 'get',
                dataType: 'application/octet-stream',
                success: function (res) {
                    console.log("Thành công")
                }
            })
        })
    </script>
</body>
</html>
  1. Phương pháp 1: Có thể sử dụng thẻ <a> để tải về, href='đường dẫn đến route/';
  2. Phương pháp 2: Sử dụng AJAX để gọi đến route tương ứng;

Để tìm hiểu thêm về thư viện xlsxwriter, tham khảo https://blog.csdn.net/qq_44670803/article/details/102776659

Thẻ: Django xlsxwriter python Excel Web Development

Đăng vào ngày 2 tháng 6 lúc 00:53