2024-06-02 01:48:07 +08:00
|
|
|
|
import json
|
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-02 01:48:07 +08:00
|
|
|
|
from django.apps import apps
|
2024-06-02 21:30:17 +08:00
|
|
|
|
from django.core.exceptions import ValidationError
|
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-02 21:30:17 +08:00
|
|
|
|
from rest_framework.decorators import api_view
|
|
|
|
|
|
|
|
|
|
from application.perf_mgnt.serializers import GroupBusinessTargetSerializer
|
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文件
|
2024-06-02 21:30:17 +08:00
|
|
|
|
response = FileResponse(open(file_path, 'rb'), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
2024-06-01 01:40:12 +08:00
|
|
|
|
# 设置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
|
|
|
|
|
|
|
|
|
|
2024-06-02 21:30:17 +08:00
|
|
|
|
@login_required
|
2024-06-01 05:05:29 +08:00
|
|
|
|
def common_excel_parse(request):
|
2024-06-01 10:13:10 +08:00
|
|
|
|
"""
|
|
|
|
|
该函数用于解析上传的Excel文件并返回数据。
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
request: HTTP请求对象,包含上传的Excel文件。
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
JsonResponse: 包含解析后的Excel数据的JSON响应,或包含错误消息的JSON响应。
|
|
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
|
N/A
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
# 如果是POST请求并且有上传的文件
|
2024-06-01 05:05:29 +08:00
|
|
|
|
if request.method == 'POST' and request.FILES:
|
2024-06-01 10:13:10 +08:00
|
|
|
|
# 获取上传的Excel文件
|
2024-06-01 05:05:29 +08:00
|
|
|
|
excel_file = request.FILES.get('excel_file')
|
|
|
|
|
|
2024-06-01 10:13:10 +08:00
|
|
|
|
# 如果没有提供文件,返回错误响应
|
2024-06-01 05:05:29 +08:00
|
|
|
|
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
|
|
|
|
|
2024-06-02 21:30:17 +08:00
|
|
|
|
# 获取fields_map和model_config
|
|
|
|
|
fields_map = json.loads(request.POST.get('fields_map', '{}'))
|
|
|
|
|
model_config = json.loads(request.POST.get('model_config', '{}'))
|
2024-06-01 05:05:29 +08:00
|
|
|
|
|
2024-06-02 21:30:17 +08:00
|
|
|
|
# 动态获取模型
|
|
|
|
|
try:
|
|
|
|
|
model = apps.get_model(model_config['app_label'], model_config['model_name'])
|
|
|
|
|
except (LookupError, KeyError):
|
|
|
|
|
return JsonResponse({'error': '模型配置错误。'}, status=400)
|
2024-06-01 05:05:29 +08:00
|
|
|
|
|
2024-06-02 21:30:17 +08:00
|
|
|
|
columns = list(fields_map.values())
|
|
|
|
|
fields = list(fields_map.keys())
|
2024-06-01 05:05:29 +08:00
|
|
|
|
|
2024-06-02 21:30:17 +08:00
|
|
|
|
# 保存文件到服务器
|
|
|
|
|
file_name = default_storage.save(excel_file.name, excel_file)
|
|
|
|
|
file_path = os.path.join(settings.MEDIA_ROOT, file_name)
|
2024-06-01 05:05:29 +08:00
|
|
|
|
|
2024-06-02 21:30:17 +08:00
|
|
|
|
try:
|
|
|
|
|
# 打开并解析Excel文件
|
|
|
|
|
workbook = load_workbook(file_path, data_only=True)
|
|
|
|
|
sheet = workbook.active
|
|
|
|
|
data = []
|
|
|
|
|
|
|
|
|
|
# 读取第一行作为表头
|
|
|
|
|
header_row = [cell.value for cell in sheet[1]]
|
|
|
|
|
|
|
|
|
|
# 检查表头是否与fields_map的values对应
|
|
|
|
|
if header_row != columns:
|
|
|
|
|
return JsonResponse({'error': '表头不匹配,请使用正确的Excel上传模板。'}, status=400)
|
|
|
|
|
|
|
|
|
|
for row in sheet.iter_rows(min_row=2, values_only=True):
|
|
|
|
|
if not all(value is None for value in row):
|
|
|
|
|
instance_data = dict(zip(fields, row))
|
|
|
|
|
instance = model(**instance_data)
|
|
|
|
|
try:
|
|
|
|
|
instance.full_clean()
|
|
|
|
|
data.append(instance)
|
|
|
|
|
except ValidationError as e:
|
|
|
|
|
return JsonResponse({'error': f'数据校验错误: {e.message_dict}'}, status=400)
|
|
|
|
|
|
|
|
|
|
# 清理,删除上传的文件
|
|
|
|
|
os.remove(file_path)
|
|
|
|
|
|
|
|
|
|
serializer = GroupBusinessTargetSerializer(data, many=True)
|
|
|
|
|
return JsonResponse(serializer.data, safe=False)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
# 清理,删除上传的文件
|
|
|
|
|
os.remove(file_path)
|
|
|
|
|
return JsonResponse({'error': f'解析文件时出错: {str(e)}'}, status=500)
|
2024-06-01 05:05:29 +08:00
|
|
|
|
|
|
|
|
|
return JsonResponse({'error': '请求错误'}, status=400)
|
2024-06-02 01:48:07 +08:00
|
|
|
|
|
|
|
|
|
|
2024-06-02 21:30:17 +08:00
|
|
|
|
@login_required
|
2024-06-02 01:48:07 +08:00
|
|
|
|
def save_excel_table_data(request):
|
|
|
|
|
if request.method == 'POST':
|
|
|
|
|
try:
|
|
|
|
|
data = json.loads(request.body)
|
2024-06-02 21:30:17 +08:00
|
|
|
|
app_label = data.get('app_label')
|
|
|
|
|
model_name = data.get('model_name')
|
|
|
|
|
table_data = data.get('table_data')
|
|
|
|
|
|
|
|
|
|
if not app_label or not model_name or not table_data:
|
|
|
|
|
return JsonResponse({'error': '缺少必要的参数'}, status=400)
|
2024-06-02 01:48:07 +08:00
|
|
|
|
|
|
|
|
|
# 使用Django的apps模块获取模型
|
|
|
|
|
Model = apps.get_model(app_label, model_name)
|
|
|
|
|
|
|
|
|
|
# 处理每一行数据
|
|
|
|
|
for row_data in table_data:
|
2024-06-02 21:30:17 +08:00
|
|
|
|
try:
|
|
|
|
|
instance = Model(**row_data)
|
|
|
|
|
instance.full_clean() # 验证数据
|
|
|
|
|
instance.save()
|
|
|
|
|
except ValidationError as e:
|
|
|
|
|
return JsonResponse({'error': f'数据校验错误: {e.message_dict}'}, status=400)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return JsonResponse({'error': f'保存数据时出错: {str(e)}'}, status=500)
|
2024-06-02 01:48:07 +08:00
|
|
|
|
|
|
|
|
|
return JsonResponse({'message': '表格数据保存成功'}, status=200)
|
2024-06-02 21:30:17 +08:00
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
|
return JsonResponse({'error': '无效的JSON格式'}, status=400)
|
2024-06-02 01:48:07 +08:00
|
|
|
|
except Exception as e:
|
2024-06-02 21:30:17 +08:00
|
|
|
|
return JsonResponse({'error': f'服务器内部错误: {str(e)}'}, status=500)
|
|
|
|
|
return JsonResponse({'error': '无效的请求方法'}, status=400)
|