首页 > 解决方案 > 如何在 Django 上使用 openpyxl 从服务器下载 Excel 表?

问题描述

我的前端通过 AJAX 调用Django -Server 获取 HTTP 请求以将数据从数据库导出到 excel 文件。因此我使用openpyxl。我想在客户端下载 HTTP 响应,但只获取无法打开或未定义数据的 excel 文件。

这是我的 javascript 请求:

$.ajax({
        url: '/documentation/export/get' + '/' + var_1 + '/' + var_2,
        type: 'get',
        responseType: 'blob',
               
        success: function(response) {
            console.log("EXCEL Success")
            // var contentType = 'application/vnd.ms-excel';
            var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            var filename = "TEST.xlsx"
          
            var blob = new Blob([response], { type: contentType });

            var downloadUrl = URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = downloadUrl;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
       }           
    });

这是我的服务器端 python 代码,views.py:

from openpyxl import Workbook
def documentation_export (request, var_1, var_2):
    
excel_data = [
  ['header1', 'header2', 'header3', 'header4', 'header5'],
  [1,4,5,6,7],
  [5,6,2,4,8]
]

if excel_data:
    wb = Workbook(write_only=True)
    ws = wb.create_sheet()
    for line in excel_data:
        ws.append(line)

response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=mydata.xlsx'
wb.save(response)

return response

excelfile / 工作簿的数据现在仍然是来自互联网的一个例子。

如果我使用发布的代码,则根本不会开始下载。如果我改用注释掉的“vnd.ms-excel”,我会得到一些损坏的 excel 文件......

我尝试了很多来自互联网的解决方案,但没有任何成功。

标签: javascriptpythondjangodjango-viewsopenpyxl

解决方案


推荐阅读