|
@@ -2,8 +2,10 @@
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
from fastapi import APIRouter, Request, Depends,Query,HTTPException
|
|
|
+from fastapi.responses import StreamingResponse
|
|
|
from database import get_db
|
|
|
from sqlalchemy.orm import Session
|
|
|
+from sqlalchemy import inspect,text
|
|
|
from fastapi.responses import JSONResponse
|
|
|
from models import *
|
|
|
from utils import *
|
|
@@ -180,6 +182,53 @@ async def userupdate(
|
|
|
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
|
|
|
|
|
|
|
|
+@router.post("/export")
|
|
|
+async def export_to_excel(
|
|
|
+ db: Session = Depends(get_db),
|
|
|
+ user_id: str = Depends(valid_access_token)
|
|
|
+):
|
|
|
+ # 获取对应填报ID的数据表名称
|
|
|
+
|
|
|
+
|
|
|
+ data_table_name = 'sys_user'
|
|
|
+ # 获取表结构(用户填报的字段)
|
|
|
+ inspector = inspect(db.bind)
|
|
|
+ columns = inspector.get_columns(data_table_name)
|
|
|
+
|
|
|
+ # 提取用户填报的字段注释
|
|
|
+ user_report_columns = [col for col in columns if col['name'] in ['user_id', 'dept_id', 'user_name', 'nick_name', 'phonenumber']]
|
|
|
+ column_comments = [col.get('comment', '') for col in user_report_columns]
|
|
|
+
|
|
|
+ # 构建查询SQL,关联 sys_user 表获取 nick_name
|
|
|
+ query_sql = f"""
|
|
|
+ SELECT {', '.join([f'rd.{col["name"]}' for col in user_report_columns])}
|
|
|
+ FROM {data_table_name} rd where del_flag<>'2'
|
|
|
+ """
|
|
|
+
|
|
|
+ # 使用 text 包装查询字符串
|
|
|
+ result = db.execute(text(query_sql))
|
|
|
+ rows = result.fetchall()
|
|
|
+ import pandas as pd
|
|
|
+ from io import BytesIO
|
|
|
+ # 将查询结果转换为 DataFrame
|
|
|
+ df = pd.DataFrame(rows, columns= column_comments)
|
|
|
+
|
|
|
+ # 将 DataFrame 导出为 Excel 文件
|
|
|
+ output = BytesIO()
|
|
|
+ with pd.ExcelWriter(output, engine='openpyxl') as writer:
|
|
|
+ df.to_excel(writer, index=False, sheet_name='用户列表')
|
|
|
+
|
|
|
+ # 设置响应头
|
|
|
+ output.seek(0)
|
|
|
+ headers = {
|
|
|
+ 'Content-Disposition': 'attachment; filename="report_data.xlsx"',
|
|
|
+ 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
|
|
+ }
|
|
|
+
|
|
|
+ # 返回文件流
|
|
|
+ return StreamingResponse(output, headers=headers)
|
|
|
+
|
|
|
+
|
|
|
|
|
|
|
|
|
|