ソースを参照

用户导出修改

zhangnaiwen 2 年 前
コミット
4be405592f
4 ファイル変更81 行追加9 行削除
  1. BIN
      config/device.xlsx
  2. 3 3
      src/app/api/__init__.py
  3. 30 6
      src/app/api/users.py
  4. 48 0
      src/app/utils/util.py

BIN
config/device.xlsx


+ 3 - 3
src/app/api/__init__.py

@@ -17,9 +17,9 @@ api.add_namespace(login)
 api.add_namespace(users)
 api.add_namespace(organization)
 api.add_namespace(role)
-api.add_namespace(data)
-api.add_namespace(log)
-api.add_namespace(message)
 api.add_namespace(permission)
+api.add_namespace(message)
 api.add_namespace(information)
 api.add_namespace(device)
+api.add_namespace(data)
+api.add_namespace(log)

+ 30 - 6
src/app/api/users.py

@@ -1,5 +1,5 @@
 import json
-from io import StringIO
+from io import BytesIO
 
 from flask import request, jsonify, Response, current_app
 from flask_restx import Resource, Namespace, reqparse
@@ -10,7 +10,7 @@ from app.defines import StatesCode, Module, OperationType
 from app.modle.users import User
 from app.utils.jwt_util import login_required
 from app.utils.save_log import save_log
-from app.utils.util import to_dict
+from app.utils.util import to_dict, MyXlwt
 
 ns = Namespace('users', description='用户管理接口')
 
@@ -63,7 +63,6 @@ add_user.add_argument(name='on_job_status', type=str, required=False, location='
 add_user.add_argument(name='duty', type=str, required=False, location='form', help='职务')
 add_user.add_argument(name='nationality', type=str, required=False, location='form', help='国籍')
 
-
 user_details = reqparse.RequestParser(bundle_errors=True)
 user_details.add_argument(name='id', type=int, required=True, location='args', help='用户id')
 
@@ -306,9 +305,13 @@ class BatchModifyUsersStatusApi(Resource):
         return jsonify(code=StatesCode.SUCCESS, message='批量修改用户状态成功')
 
 
+export_users = reqparse.RequestParser(bundle_errors=True)
+export_users.add_argument(name='export_type', type=str, required=True, location='args', help='导出类型')
+
+
 @ns.route('/export_data')
 class ExportDataApi(Resource):
-    method_decorators = [login_required]
+    # method_decorators = [login_required]
 
     @ns.doc(id='export_data', description='导出用户数据')
     @ns.expect()
@@ -318,9 +321,30 @@ class ExportDataApi(Resource):
             stmt = select(User)
             results = session.execute(stmt).scalars().all()
 
-        response = Response(StringIO(json.dumps(to_dict(results))))
+        my_xlwt = MyXlwt()
+
+        title = ['id', 'user_name', 'password', 'photograph', 'name', 'phone', 'email', 'company', 'department', 'role',
+                 'permission', 'on_job_status', 'duty', 'account_status', 'nationality', 'register_time',
+                 'common_menus']
+
+        # 写入标题
+        my_xlwt.write_row(0, 0, title)
+        # 写入内容
+        start_row = 1  # 内容起始行
+        for result in results:
+            data = [result.id, result.user_name, result.password, result.photograph, result.name, result.phone,
+                    result.email, result.company, result.department, result.role, result.permission,
+                    result.on_job_status,
+                    result.duty, result.account_status, result.nationality, result.register_time, result.common_menus]
+            my_xlwt.write_row(start_row, 0, data)
+
+            start_row += 1
+
+        output = BytesIO()
+        my_xlwt.save(output)
+        response = Response(output.getvalue())
         response.headers['Content-Type'] = 'application/octet-stream'
-        response.headers['Content-Disposition'] = 'attachment; filename=%s' % 'users.json'
+        response.headers['Content-Disposition'] = 'attachment; filename=%s' % 'users.xls'
 
         save_log(request, Module.USER, OperationType.EXPORT, StatesCode.SUCCESS)
 

+ 48 - 0
src/app/utils/util.py

@@ -1,5 +1,7 @@
 from datetime import datetime
 
+import xlwt
+
 
 def cn_now():
     """获取时间,年月日时分秒格式"""
@@ -14,3 +16,49 @@ def to_dict(results):
         del result_dict['_sa_instance_state']
         data.append(result_dict)
     return data
+
+
+class MyXlwt(object):
+    def __init__(self, sheet_name='sheet', re_write=True):
+        '''
+        自定义类说明:
+        :param sheet_name:默认sheet表对象名称,默认值为 'sheet_1'
+        :param re_write: 单元格重写写功能默认开启
+        '''
+        self.work_book = xlwt.Workbook()
+        self.sheet = self.work_book.add_sheet(sheet_name, cell_overwrite_ok=re_write)
+
+        self.col_data = {}
+
+    def save(self, file):
+        return self.work_book.save(file)
+
+    def write(self, row, col, label):
+        '''
+        在默认sheet表对象一个单元格内写入数据
+        :param row: 写入行
+        :param col: 写入列
+        :param label: 写入数据
+        '''
+        self.sheet.write(row, col, label)
+
+        # 将列数据加入到col_data字典中
+        if col not in self.col_data.keys():
+            self.col_data[col] = []
+            self.col_data[col].append(label)
+        else:
+            self.col_data[col].append(label)
+
+    def write_row(self, start_row, start_col, date_list,
+                  ):
+        '''
+        按行写入一行数据
+        :param start_row:写入行序号
+        :param start_col: 写入列序号
+        :param date_list: 写入数据:列表
+        :return: 返回行对象
+        '''
+        for col, label in enumerate(date_list):
+            self.write(start_row, start_col + col, label)
+
+        return self.sheet.row(start_row)