Ant-Design-Pro-V5: ProTable前端导出excel表格。

news2024/9/25 13:24:58

Prtable表格中根据搜索条件实现excel表格导出。
在这里插入图片描述
代码展示:

index.jsx

import React, { useRef, useState, Fragment, useEffect } from 'react';
import { getLecturerList, lecturerExportExcel } from '@/services/train/personnel';
import { getOrgList, getSelectType } from '@/services/globalServices';
import { PlusOutlined, EditTwoTone, ExportOutlined } from '@ant-design/icons';
import { PageContainer, ProTable, ProFormSelect } from '@ant-design/pro-components';
import { Button, message, Form, Space, Tooltip, Spin } from 'antd';
import { FormattedMessage } from 'umi';

const InsideLecturer = () => {
  const [orgList, setOrgList] = useState([]); // 管理机构
  const [downloadParams, setDownloadParams] = useState({}); //导出参数
  const [downloadTotal, setDownloadTotal] = useState({}); //导出数量总数以及页码
  const [exportExcelLoading, setExportExcelLoading] = useState(false); //导出loading
  const actionRef = useRef(); // 表格组件ProTable ref
  const [form] = Form.useForm(); // 创建表单
  const [currentRow, setCurrentRow] = useState(); // 当前行数据
  const [teacherstateArray, setTeacherstateArray] = useState([]); // 在岗状态
  const [teacherstateObj, setTeacherstateObj] = useState({}); // 在岗状态
  const [teacherTypeArray, setTeacherTypeArray] = useState([]); // 讲师类型
  const [teacherTypeObj, setTeacherTypeObj] = useState({}); // 讲师类型
  const [idtypeArray, setIdtypeArray] = useState([]); // 证件类型

  const teacherType = 2; // 内勤讲师类型
  useEffect(() => {
    getSelectTypeFun();
  }, []);
  const getSelectTypeFun = async () => {
    await getSelectType('teacherstate').then((res) => {
      if (res && res.data) {
        setTeacherstateArray(res.data);
        let Obj = {};
        res.data.forEach((item) => {
          Obj[item.code] = item.codeName;
        });
        setTeacherstateObj(Obj);
      }
    });
    await getSelectType('teachertype').then((res) => {
      if (res && res.data && res.data.length > 0) {
        let removedArr = res.data.filter((item) => {
          return item.code != '1' && item.code != '3';
        });
        setTeacherTypeArray(removedArr);
        let Obj = {};
        removedArr.forEach((item) => {
          Obj[item.code] = item.codeName;
        });
        setTeacherTypeObj(Obj);
      }
    });
    await getSelectType('idnotype').then((res) => {
      if (res && res.data) {
        setIdtypeArray(res.data);
      }
    });
  };
  const fieldNames = {
    label: 'codeName',
    value: 'code',
  };
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '讲师类别',
      dataIndex: 'teacherType',
      valueType: 'select',
      fieldProps: {
        options: teacherTypeArray,
        fieldNames,
      },
    },
    {
      title: '证件号码',
      dataIndex: 'idNo',
    },
    {
      title: '工号',
      dataIndex: 'staffCode',
      search: false,
      editable: false,
    },
    {
      title: '讲师状态',
      dataIndex: 'state',
      valueType: 'select',
      fieldProps: {
        options: teacherstateArray,
        fieldNames,
      },
    },
    {
      title: '移动电话',
      dataIndex: 'mobile',
      search: false,
      width: 150,
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" />,
      dataIndex: 'option',
      valueType: 'option',
      width: 100,
      render: (_, record) => [
        <div key={record.staffCode}>
          <Fragment>
            <a
              onClick={() => {
                setCurrentRow(record);
              }}
            >
              <EditTwoTone />
              <FormattedMessage id="pages.searchTable.edit" />
            </a>
            <span style={{ marginRight: '10px' }}></span>
          </Fragment>
        </div>,
      ],
    },
  ];

  return (
    <Spin spinning={exportExcelLoading} tip="数据导出中...">
      <PageContainer breadcrumb={false}>
        <ProTable
          headerTitle="查询列表"
          rowKey={'staffCode'}
          actionRef={actionRef}
          options={false}
          search={{
            labelWidth: 120,
          }}
          params={{
            teacherType: 2,
          }}
          pagination={{
            pageSize: 10,
          }}
          tableAlertOptionRender={() => {
            return false;
          }}
          toolBarRender={() => [
            <Tooltip placement="topLeft" title="点击导出内容">
              <Button
                type="default"
                key="export"
                loading={exportExcelLoading}
                onClick={() => {
                  lecturerExportExcel({
                    downloadTotal,
                    downloadParams,
                    orgObj2,
                    teacherstateObj,
                    teacherType,
                    teacherTypeObj,
                    setExportExcelLoading,
                  });
                }}
              >
                <ExportOutlined /> 导出数据
              </Button>
            </Tooltip>,
          ]}
          revalidateOnFocus={false}
          onSubmit={(params) => {
            // 导出参数设置
            setDownloadParams(params);
          }}
          onReset={() => setDownloadParams(undefined)}
          request={(params) => {
            const res = getLecturerList({ ...params });
            res.then((value) => {
              // 设置导出总数以及页码
              setDownloadTotal({
                current: 1,
                pageSize: value?.total || 100000,
              });
            });
            return res;
          }}
          columns={columns}
        />
      </PageContainer>
    </Spin>
  );
};

export default InsideLecturer;

数据字典格式返回:
在这里插入图片描述
以 teacherTypeObj 为例 向services.js中 lecturerExportExcel 方法中传入的格式为:
在这里插入图片描述

services.js中 lecturerExportExcel 导出方法:

import { request } from 'umi';
import { paramsFilter } from '../../utils/utils';
import ExportJsonExcel from 'js-export-excel';
import { message } from 'antd';


export async function lecturerExportExcel(params) {
  const { downloadTotal, downloadParams, orgObj2, teacherstateObj, teacherType, teacherTypeObj, setExportExcelLoading } = params;
  setExportExcelLoading(true);
  // 参数合并
  let newParams = Object.assign(downloadTotal, downloadParams);
  newParams.teacherType = teacherType;
  const result = await request('/api/Info/list2', {
    params: paramsFilter(newParams),
  });
  // 根据实际情况注释不需要导出的字段
  const allowExportColumns = [
    'manageCom',
    'name',
    'staffCode',
    'idNo',
    'mobile',
    "state",
    "teacherType"
  ];
  const TableItemObject = {
    manageCom: "管理机构",
    name: "姓名",
    staffCode: "工号",
    idNo: "证件号码",
    mobile: "移动电话",
    state: "讲师状态",
    teacherType: '讲师类别'
  };

  const cnColumns = allowExportColumns.map(kk => TableItemObject[kk]);
  if (Array.isArray(result?.data) && result?.data.length > 0) {
    const tableData = [];
    result?.data.forEach((item) => {
      const kv = {};
      Object.keys(item).map(vv => {
        if (allowExportColumns.includes(vv)) {
          // 数据字典字段汉化
          if (vv === 'manageCom') {
            kv[TableItemObject[vv]] = orgObj2[item[vv]] || '';
          } else if (vv === 'state') {
            kv[TableItemObject[vv]] = teacherstateObj[item[vv]] || '';
          } else if (vv === 'teacherType') {
            kv[TableItemObject[vv]] = teacherTypeObj[item[vv]] || '';
          } else {
            // 不用汉化直接输出
            kv[TableItemObject[vv]] = item[vv];
          }
        }
      })
      tableData.push(kv);
    });
    const option = {
      fileName: "讲师信息",
      datas: [
        {
          sheetData: tableData,// 数据
          sheetName: 'sheet1',
          sheetFilter: cnColumns,// 表头
          sheetHeader: cnColumns,// 表头
        }
      ]
    }
    const toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
    setExportExcelLoading(false);
    return true;
  }
  message.error('数据为空!');
  setExportExcelLoading(false);
  return false;
}

utils 中 paramsFilter 方法:过滤无用参数

// 接口请求参数中 删除对象中值为空或null或undefined或者为空的所有属性
export function paramsFilter(requestParams) {
  let newParams = Object.keys(requestParams)
    .filter((key) => requestParams[key] !== null && requestParams[key] !== undefined && requestParams[key] !== '')
    .reduce((acc, key) => ({ ...acc, [key]: requestParams[key] }), {});
  return newParams;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/957966.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

打击儿童性虐待,遭多家机构反对,苹果宣布停止开发CSAM检测计划

据报道&#xff0c;苹果公司曾计划在其iCloud云服务中引入一项儿童性虐待资料&#xff08;CSAM&#xff09;检测计划&#xff0c;但由于反对声浪日益高涨&#xff0c;该计划最终宣布停止开发。CSAM检测计划的原本目的是为了帮助阻止儿童性虐待资料的传播&#xff0c;保护儿童的…

实例418 通过串口发送数据

实例说明 现在大多数硬件设备均采用串口技术与计算机相连&#xff0c;因此串口的应用程序开发越来越普遍。例如&#xff0c;在计算机没有安装网卡的情况下&#xff0c;将本机上的一些信息数据传输到另一台计算机上&#xff0c;那么利用串口通信就可以实现。运行本程序&#xff…

QQ聊天记录在哪个文件夹?(针对iPhone用户的详细教程)

苹果手机的QQ聊天记录一般存放在哪里&#xff1f;问了很多朋友都不知道&#xff0c;试了网上很多方法都没用&#xff0c;大家还有其他解决方法吗&#xff1f; 很多iPhone用户都不知道QQ聊天记录保存在哪个文件夹&#xff0c;这是很正常的现象。因为iPhone手机本身是不具备【文件…

Gatling 入门

1.新建一个测试接口项目 里面代码非常简单&#xff0c;就一个hi接口&#xff1a; package com.example.gatlingdemo.controller;import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;import java.ti…

北京开发APP的费用明细

开发APP项目时&#xff0c;在功能确定后需要知道有哪些可能的费用&#xff0c;安排项目预算。北京开发APP的费用明细可能会包括以下几个部分&#xff0c;每个部分都会产生一些费用。今天和大家分享APP费用明细有哪些&#xff0c;希望对大家有所帮助。北京木奇移动技术有限公司&…

地理测绘基础知识(4) 照射计算

照射计算&#xff0c;是一种常用的三维几何计算。已知一个光源的光强图&#xff0c;计算光源投射到地表各处的功率密度。这种计算需求可以直观的理解为计算已知位置、指向、聚光特性的手电筒&#xff0c;计算地表某地点强度。 本文的推导涉及很多旋转&#xff0c;很容易出错和…

ElasticSearch安装为Win11服务

在windows的环境下操作是Elasticsearch,并且喜欢使用命令行 &#xff0c;启动时通过cmd直接在elasticsearch的bin目录下执行elasticsearch ,这样直接启动的话集群名称会默elasticsearch&#xff0c;节点名称会随机生成。 停止就直接在cmd界面按CtrlC 其实我们也可以将elasticse…

Ansible学习笔记14

实现多台的分离实现&#xff1a; [rootlocalhost playbook]# cat example3.yaml --- - hosts: 192.168.17.105remote_user: roottasks:- name: create test1 directoryfile: path/test1/ statedirectory- hosts: 192.168.17.106remote_user: roottasks:- name: create test2 d…

Python—匹配字段

1. 「概述」 在日常开发中&#xff0c;经常需要对数据中的某些字段进行匹配&#xff0c;但这些字段可能存在微小的差异。例如&#xff0c;同一个招聘岗位的数据中&#xff0c;省份字段可能有“广西”、“广西壮族自治区”和“广西省”等不同的写法。为了处理这些情况&#xff…

二叉树的介绍

写在前面&#xff1a; 二叉树是数据结构课程中非常重要的内容&#xff0c;我们针对二叉树的概念、性质以及类型展开详细介绍。 一、概念 二叉树&#xff08;Binary Tree&#xff09;是n&#xff08;n>0&#xff09;个结点的有限集合&#xff0c;该集合或者空集&#xff0…

C语言用递归函数求解斐波那契数

int Fib(int n) {if (n 1 || n 2){return 1;}return Fib(n - 1) Fib(n - 2); }int main() {int i 0;printf("请输入需要第几个斐波那契数\n");scanf("%d", &i);int r Fib(i);printf("%d\n", r);return 0; }

JVM 对象的内存布局

对象头 Mark word 标记字段 用于存储对象自身的运行时数据&#xff0c;如哈希码&#xff08;HashCode&#xff09;、GC分代年龄、锁状态标志、线程持有的锁、偏向线程ID、偏向时间戳等 ClassPoint 类型指针 对象指向它的类型元数据的指针&#xff0c;Java虚拟机通过这个指针 来…

C++——shared_ptr:make_shared的用处,与shared_ptr直接构造的区别

shared_ptr shared_ptr继承自__shared_ptr&#xff0c;其中有两个对象&#xff0c;一个是指向资源的指针&#xff0c;一个是控制块&#xff0c;指向一个引用计数对象。控制块中存储了强引用和弱引用的计数&#xff0c;强引用Uses代表shared_ptr对象的引用计数&#xff0c;弱引…

excel怎么设置任意选一个单元格纵横竖横都有颜色

有时excel表格内容过多的时候&#xff0c;我们通过excel设置任意选一个单元格纵横&#xff0c;竖横背景颜色&#xff0c;这样会更加具有辨识度。设置方式截图如下 设置成功后&#xff0c;预览的效果图

常静相伴:深度解析C++中的const与static关键字

个人主页&#xff1a;北海 &#x1f390;CSDN新晋作者 &#x1f389;欢迎 &#x1f44d;点赞✍评论⭐收藏✨收录专栏&#xff1a;C/C&#x1f91d;希望作者的文章能对你有所帮助&#xff0c;有不足的地方请在评论区留言指正&#xff0c;大家一起学习交流&#xff01;&#x1f9…

kafka 命令脚本说明以及在java中使用

一、命令行使用 1.1、topic 命令 1、关于topic,这里用window 来示例 bin\windows\kafka-topics.bat2、创建 first topic,五个分区&#xff0c;1个副本 bin\windows\kafka-topics.bat --bootstrap-server localhost:9092 --create --partitions 5 --replication-factor 1 -…

nacos import com.alibaba.nacos.consistency.entity.ReadRequest

1. 异常情况 import com.alibaba.nacos.consistency.entity.ReadRequest; import com.alibaba.nacos.consistency.entity.Response; import com.alibaba.nacos.consistency.entity.WriteRequest; 2. 解决方法 安装插件&#xff0c;然后重新编译 记住选择Java8

从零做软件开发项目系列之十——项目运维

项目结项后的运维阶段是确保软件持续稳定运行、修复问题、满足用户需求的关键时期。在这个阶段&#xff0c;需要建立有效的维护制度&#xff0c;关注各种问题&#xff0c;并采取相应措施来保障系统的可靠性和可持续性。 1 运维团队 开展服务运维工作&#xff0c;首先需要组建运…

07.Knowing When to Look

目录 前言泛读摘要Introduction小结 精讲方法Encoder-Decoder框架 for Image CaptioningSpatial Attention ModelAdaptive Attention Model Implementation DetailsEncoder-CNNDecoder-RNNTraining details Related Work实验结论 前言 本课程来自深度之眼《多模态》训练营&…

【前端】Vue2 脚手架模块化开发 -快速入门

&#x1f384;欢迎来到边境矢梦的csdn博文&#x1f384; &#x1f384;本文主要梳理Vue2 脚手架模块化开发 &#x1f384; &#x1f308;我是边境矢梦&#xff0c;一个正在为秋招和算法竞赛做准备的学生&#x1f308; &#x1f386;喜欢的朋友可以关注一下&#x1faf0;&#x…