216 lines
7.5 KiB
Python
216 lines
7.5 KiB
Python
"""
|
||
数据导出 API:JSON / XLSX / CSV
|
||
"""
|
||
import re
|
||
import csv
|
||
import io as io_module
|
||
from datetime import datetime
|
||
from urllib.parse import quote
|
||
from flask import Blueprint, request, jsonify, send_file
|
||
from database import (
|
||
get_form, get_preset, get_form_submissions, get_form_files,
|
||
insert_business_metric, get_versions_as_of, build_status_students,
|
||
)
|
||
from config import OPENPYXL_AVAILABLE
|
||
from routes.auth import require_login
|
||
|
||
bp = Blueprint('export', __name__)
|
||
|
||
|
||
@bp.route('/api/export/<form_id>')
|
||
@require_login
|
||
def api_export_data(form_id):
|
||
"""导出表单数据,支持 JSON 和 XLSX 格式"""
|
||
try:
|
||
export_format = request.args.get('format', 'json')
|
||
as_of = request.args.get('asOf', '').strip()
|
||
|
||
form = get_form(form_id)
|
||
if not form:
|
||
return jsonify(error='表单不存在'), 404
|
||
|
||
preset_id = form.get('presetId')
|
||
|
||
if as_of:
|
||
# 按时间点导出:每个身份取该时间点的最新历史版本
|
||
versions_map = get_versions_as_of(form_id, as_of)
|
||
students = build_status_students(form, versions_map=versions_map)
|
||
else:
|
||
submissions = get_form_submissions(form_id)
|
||
students = build_status_students(form, submissions)
|
||
|
||
status_data = {
|
||
"formTitle": form.get('title', '未命名表单'),
|
||
"formId": form_id,
|
||
"total": len(students),
|
||
"submitted": len([s for s in students if s['submitted']]),
|
||
"students": students
|
||
}
|
||
|
||
if export_format == 'json':
|
||
try:
|
||
insert_business_metric('data_exports', 1)
|
||
except Exception:
|
||
pass
|
||
return jsonify({
|
||
'form': form,
|
||
'submissions': status_data
|
||
})
|
||
|
||
elif export_format == 'xlsx':
|
||
if not OPENPYXL_AVAILABLE:
|
||
return jsonify(error='openpyxl未安装,无法导出Excel'), 500
|
||
try:
|
||
insert_business_metric('data_exports', 1)
|
||
except Exception:
|
||
pass
|
||
return export_to_excel(form_id, form, status_data)
|
||
|
||
elif export_format == 'csv':
|
||
csv_io = io_module.StringIO()
|
||
writer = csv.writer(csv_io)
|
||
|
||
headers = ['学号', '姓名', '提交状态', '文件列表']
|
||
writer.writerow(headers)
|
||
|
||
for student in status_data.get('students', []):
|
||
files = ', '.join([f['filename']
|
||
for f in student.get('files', [])])
|
||
writer.writerow([
|
||
student.get('id', ''),
|
||
student.get('name', ''),
|
||
'已提交' if student.get('submitted') else '未提交',
|
||
files
|
||
])
|
||
|
||
csv_io.seek(0)
|
||
|
||
form_title = '未知表单'
|
||
try:
|
||
form_info = get_form(form_id)
|
||
if form_info:
|
||
form_title = form_info.get('title', '未知表单')
|
||
form_title = re.sub(r'[<>"/\\|?*]', '', form_title)[:20]
|
||
except:
|
||
pass
|
||
|
||
csv_filename = f'{form_title}_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
|
||
try:
|
||
ascii_csv = csv_filename.encode('ascii', 'ignore').decode()
|
||
except:
|
||
ascii_csv = f'form_{form_id}_export.csv'
|
||
encoded_csv = quote(csv_filename, safe='')
|
||
|
||
try:
|
||
insert_business_metric('data_exports', 1)
|
||
except Exception:
|
||
pass
|
||
|
||
return csv_io.getvalue(), 200, {
|
||
'Content-Type': 'text/csv; charset=utf-8-sig',
|
||
'Content-Disposition': f"attachment; filename=\"{ascii_csv}\"; filename*=UTF-8''{encoded_csv}",
|
||
'Cache-Control': 'no-cache, no-store, must-revalidate'
|
||
}
|
||
|
||
else:
|
||
return jsonify(error='不支持的导出格式'), 400
|
||
|
||
except Exception as e:
|
||
print(f"导出数据失败: {str(e)}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
return jsonify(error=str(e)), 500
|
||
|
||
|
||
def export_to_excel(form_id, form_config, status_data):
|
||
"""导出数据到 Excel 文件"""
|
||
from openpyxl import Workbook
|
||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
||
from io import BytesIO
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "表单数据"
|
||
|
||
header_font = Font(bold=True, color="FFFFFF")
|
||
header_fill = PatternFill(start_color="366092",
|
||
end_color="366092", fill_type="solid")
|
||
header_alignment = Alignment(horizontal="center", vertical="center")
|
||
cell_alignment = Alignment(horizontal="left", vertical="center")
|
||
border = Border(
|
||
left=Side(style='thin'),
|
||
right=Side(style='thin'),
|
||
top=Side(style='thin'),
|
||
bottom=Side(style='thin')
|
||
)
|
||
|
||
non_file_fields = [f for f in form_config.get('fields', []) if f['type'] not in ('file', 'page_break')]
|
||
field_names = [f['name'] for f in non_file_fields]
|
||
|
||
headers = ['学号', '姓名', '提交状态'] + field_names + ['文件列表']
|
||
for col, header in enumerate(headers, 1):
|
||
cell = ws.cell(row=1, column=col, value=header)
|
||
cell.font = header_font
|
||
cell.fill = header_fill
|
||
cell.alignment = header_alignment
|
||
cell.border = border
|
||
|
||
row_num = 2
|
||
for student in status_data.get('students', []):
|
||
ws.cell(row=row_num, column=1, value=student.get('id', ''))
|
||
ws.cell(row=row_num, column=2, value=student.get('name', ''))
|
||
ws.cell(row=row_num, column=3,
|
||
value='已提交' if student.get('submitted') else '未提交')
|
||
|
||
student_data = student.get('data', {})
|
||
for col, field_name in enumerate(field_names, 4):
|
||
value = student_data.get(field_name, '')
|
||
ws.cell(row=row_num, column=col, value=value)
|
||
|
||
files = ', '.join([f['filename'] for f in student.get('files', [])])
|
||
ws.cell(row=row_num, column=len(headers), value=files)
|
||
|
||
for col in range(1, len(headers) + 1):
|
||
cell = ws.cell(row=row_num, column=col)
|
||
cell.border = border
|
||
cell.alignment = cell_alignment
|
||
|
||
row_num += 1
|
||
|
||
for col in range(1, len(headers) + 1):
|
||
col_letter = chr(64 + col) if col <= 26 else chr(64 +
|
||
(col - 1) // 26) + chr(65 + (col - 1) % 26)
|
||
ws.column_dimensions[col_letter].width = 20
|
||
|
||
output = BytesIO()
|
||
wb.save(output)
|
||
output.seek(0)
|
||
|
||
form_title = form_config.get('title', '未命名表单')
|
||
safe_title = "".join(
|
||
[c for c in form_title if c.isalnum() or c in (' ', '-', '_')]).strip()
|
||
|
||
time_str = datetime.now().strftime('%Y%m%d_%H%M%S')
|
||
excel_filename = f'{safe_title}_{time_str}.xlsx'
|
||
try:
|
||
ascii_filename = excel_filename.encode('ascii', 'ignore').decode()
|
||
if not ascii_filename:
|
||
ascii_filename = f'export_{form_id}.xlsx'
|
||
except:
|
||
ascii_filename = f'export_{form_id}.xlsx'
|
||
|
||
encoded_filename = quote(excel_filename, safe='')
|
||
|
||
response = send_file(
|
||
output,
|
||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||
as_attachment=True,
|
||
download_name=ascii_filename
|
||
)
|
||
|
||
disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
|
||
response.headers['Content-Disposition'] = disposition
|
||
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
|
||
|
||
return response
|