javascript - 如何在 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 文件......
我尝试了很多来自互联网的解决方案,但没有任何成功。
解决方案
推荐阅读
- python - 如何仅覆盖所需的图像?
- java - 如何将 MongoDB 查询转换为 Spring 数据查询
- azure-devops - 在 Azure DevOps API 调用上指定全局时间范围
- java - 通过 Google Maps API 获取当前位置
- sql - 在查询中插入替换函数
- javascript - 是否所有打算被其他类使用的 TypeScript 类都需要显式导出和导入?
- c# - 如何解决调用 Amazon SP-API 的问题,该 API 始终返回未经授权,即使使用有效的令牌和签名也是如此
- odata - Microsoft.OData.ODataException - URI 中指定的查询无效。在类型上找不到名为“标签”的属性
- flutter - Flutter Riverpod 小部件调用了两次
- flutter - 如何设置 BottomNavigationBarItem 标签的样式