import os
import urllib.parse
from openpyxl import load_workbook
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.staticfiles import finders
from django.core.files.storage import default_storage
from django.http import FileResponse, HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
@login_required
def download_excel_template(request, template_name):
"""
该视图提供下载指定的Excel模板文件。
参数:
request: HttpRequest对象。
template_name: 请求下载的Excel模板文件的名称,期望是一个字符串。
返回:
FileResponse对象,允许用户下载指定的Excel模板文件。
如果文件未找到,则返回一个HttpResponseNotFound响应。
"""
# 使用finders.find()根据文件名在Django的静态文件目录中查找文件的绝对路径
file_path = finders.find(f'excels/{template_name}')
# 如果文件路径不存在,返回404响应
if not file_path:
return HttpResponseNotFound('
文件未找到
')
# 创建FileResponse对象,设置为以附件形式下载,设置MIME类型为Excel文件
response = FileResponse(open(file_path, 'rb'),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# 设置Content-Disposition头,告诉浏览器这是一个需要下载的文件
# 使用urllib.parse.quote对文件名进行URL编码,以确保文件名中包含的特殊字符不会引起问题
response['Content-Disposition'] = f'attachment; filename="{urllib.parse.quote(template_name)}"'
return response
@csrf_exempt
def common_excel_parse(request):
if request.method == 'POST' and request.FILES:
excel_file = request.FILES.get('excel_file')
if not excel_file:
return JsonResponse({'error': '没有提供文件。'}, status=400)
# 保存文件到服务器
file_name = default_storage.save(excel_file.name, excel_file)
file_path = os.path.join(settings.MEDIA_ROOT, file_name)
# 打开并解析Excel文件
workbook = load_workbook(file_path, data_only=True)
sheet = workbook.active
data = []
# 读取数据,跳过标题行
for row in sheet.iter_rows(min_row=2, values_only=True):
# 过滤掉全是 None 的行
if not all(value is None for value in row):
data.append(row)
# 清理,删除上传的文件
os.remove(file_path)
# 返回JSON响应
return JsonResponse(data, safe=False)
return JsonResponse({'error': '请求错误'}, status=400)