XH_Digital_Management/common/views.py

73 lines
2.7 KiB
Python
Raw Normal View History

2024-06-01 05:05:29 +08:00
import os
2024-06-01 00:57:14 +08:00
import urllib.parse
2024-05-30 17:06:23 +08:00
2024-06-01 05:05:29 +08:00
from openpyxl import load_workbook
from django.conf import settings
2024-06-01 01:40:12 +08:00
from django.contrib.auth.decorators import login_required
2024-06-01 00:57:14 +08:00
from django.contrib.staticfiles import finders
2024-06-01 05:05:29 +08:00
from django.core.files.storage import default_storage
from django.http import FileResponse, HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
2024-06-01 00:57:14 +08:00
2024-06-01 01:40:12 +08:00
@login_required
2024-06-01 00:57:14 +08:00
def download_excel_template(request, template_name):
2024-06-01 01:40:12 +08:00
"""
该视图提供下载指定的Excel模板文件
2024-06-01 00:57:14 +08:00
2024-06-01 01:40:12 +08:00
参数:
request: HttpRequest对象
template_name: 请求下载的Excel模板文件的名称期望是一个字符串
返回:
FileResponse对象允许用户下载指定的Excel模板文件
如果文件未找到则返回一个HttpResponseNotFound响应
"""
# 使用finders.find()根据文件名在Django的静态文件目录中查找文件的绝对路径
2024-06-01 00:57:14 +08:00
file_path = finders.find(f'excels/{template_name}')
2024-06-01 01:40:12 +08:00
# 如果文件路径不存在返回404响应
2024-06-01 00:57:14 +08:00
if not file_path:
return HttpResponseNotFound('<h1>文件未找到</h1>')
2024-06-01 01:40:12 +08:00
# 创建FileResponse对象设置为以附件形式下载设置MIME类型为Excel文件
response = FileResponse(open(file_path, 'rb'),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# 设置Content-Disposition头告诉浏览器这是一个需要下载的文件
# 使用urllib.parse.quote对文件名进行URL编码以确保文件名中包含的特殊字符不会引起问题
2024-06-01 00:57:14 +08:00
response['Content-Disposition'] = f'attachment; filename="{urllib.parse.quote(template_name)}"'
return response
2024-06-01 05:05:29 +08:00
@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:
2024-06-01 06:30:19 +08:00
return JsonResponse({'error': '没有提供文件。'}, status=400)
2024-06-01 05:05:29 +08:00
# 保存文件到服务器
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 = []
# 读取数据,跳过标题行
2024-06-01 06:30:19 +08:00
for row in sheet.iter_rows(min_row=2, values_only=True):
2024-06-01 05:05:29 +08:00
# 过滤掉全是 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)