excel.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. from fastapi import APIRouter, File, UploadFile, Form, BackgroundTasks, Depends
  2. from fastapi.responses import JSONResponse, FileResponse
  3. from starlette.websockets import WebSocket
  4. from app.api import get_current_user, get_current_user_websocket
  5. from app.models import UserModel
  6. from app.utils.excelmerge.conformity import run_conformity
  7. import shutil
  8. import os
  9. router = APIRouter()
  10. ALLOWED_EXTENSIONS = {'xlsx'}
  11. EXCEL_FILES_PATH = 'data/output'
  12. SOURCE_FILES_PATH = 'data/source'
  13. def allowed_file(filename: str) -> bool:
  14. return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  15. def create_dir_if_not_exists(path: str):
  16. if not os.path.exists(path):
  17. os.makedirs(path)
  18. def clear_directory(path: str) -> dict:
  19. for filename in os.listdir(path):
  20. file_path = os.path.join(path, filename)
  21. try:
  22. if os.path.isfile(file_path) or os.path.islink(file_path):
  23. os.unlink(file_path)
  24. elif os.path.isdir(file_path):
  25. shutil.rmtree(file_path)
  26. except Exception as e:
  27. return {"error": "清空出错"}
  28. return {"message": "目录已清空"}
  29. def user_file_path(userid: str, path: str) -> str:
  30. return os.path.join(path, userid)
  31. @router.post('/excel/upload')
  32. async def upload_file(files: list[UploadFile] = File(...), current_user: UserModel = Depends(get_current_user)):
  33. user_id = str(current_user.id)
  34. if not any(file.filename for file in files):
  35. return JSONResponse(content={"error": "没有文件部分"}, status_code=400)
  36. if not user_id:
  37. return JSONResponse(content={"error": "缺少参数user_id"}, status_code=400)
  38. user_source = user_file_path(user_id, SOURCE_FILES_PATH)
  39. user_excel = EXCEL_FILES_PATH
  40. create_dir_if_not_exists(user_source)
  41. create_dir_if_not_exists(user_excel)
  42. clear_directory(user_source)
  43. save_path_list = []
  44. for file in files:
  45. if file.filename == '':
  46. return JSONResponse(content={"error": "没有选择文件"}, status_code=400)
  47. if file and allowed_file(file.filename):
  48. save_path = os.path.join(user_source, file.filename)
  49. with open(save_path, 'wb') as buffer:
  50. shutil.copyfileobj(file.file, buffer)
  51. save_path_list.append(save_path)
  52. else:
  53. return JSONResponse(content={"error": "不允许的文件类型"}, status_code=400)
  54. return JSONResponse(content={"code": 200, "msg": "", "data": {}}, status_code=200)
  55. # ws://localhost:9201/api/document/ws/excel
  56. @router.websocket("/ws/excel")
  57. async def ws_excel(websocket: WebSocket, current_user: UserModel = Depends(get_current_user_websocket)):
  58. await websocket.accept()
  59. user_id = str(current_user.id)
  60. user_source = user_file_path(user_id, SOURCE_FILES_PATH)
  61. user_excel = EXCEL_FILES_PATH
  62. create_dir_if_not_exists(user_source)
  63. create_dir_if_not_exists(user_excel)
  64. while True:
  65. data = await websocket.receive_text()
  66. try:
  67. if data == "\"合并Excel\"":
  68. merge_file = run_conformity(user_source, user_excel)
  69. if merge_file is not None:
  70. await websocket.send_json({
  71. "message": "文档合并成功!",
  72. "type": "stream",
  73. "file_name": f"{merge_file}.xlsx",
  74. "download_url": f"./api/document/download/{merge_file}.xlsx"
  75. })
  76. await websocket.send_json({
  77. "message": "文档合并成功!",
  78. "type": "close",
  79. })
  80. else:
  81. await websocket.send_json({"error": "合并失败", "type": "stream", "files": []})
  82. else:
  83. print(f"Received data: {data}")
  84. await websocket.send_json({"error": "未知指令", "data": str(data)})
  85. except Exception as e:
  86. await websocket.send_json({"error": str(e)})
  87. await websocket.close()
  88. @router.get("/download/{file_full_name}")
  89. async def download_file(background_tasks: BackgroundTasks, file_full_name: str):
  90. file_name = os.path.basename(file_full_name)
  91. user_excel = EXCEL_FILES_PATH
  92. file_path = os.path.join(user_excel, file_full_name)
  93. if not os.path.exists(file_path):
  94. return JSONResponse(content={"error": "文件不存在"}, status_code=404)
  95. def delete_file():
  96. try:
  97. os.unlink(file_path)
  98. except OSError as e:
  99. print(f"Deleting file error")
  100. # 待下载完成后删除生成的文件
  101. background_tasks.add_task(delete_file)
  102. return FileResponse(path=file_path, filename=file_name,
  103. media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")