index.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { formatDate } from "@/utils/downloadFile";
  2. import { CloudDownloadOutlined } from "@ant-design/icons";
  3. import { Button, message } from "antd";
  4. import moment from "moment";
  5. import React from 'react'
  6. /**
  7. *
  8. * @param api 需要再请求设置 responseType: 'blob' 返回blob数据
  9. * @returns
  10. */
  11. function DownloadExcel(props: { api: any, querys: any }) {
  12. const { api, querys } = props
  13. const downloadFile = (data: any, type: any, fileName: string) => {
  14. let blob = new Blob([data], { type: `application/${type};charset=utf-8` });
  15. let downloadElement = document.createElement('a');
  16. let href = window.URL.createObjectURL(blob);
  17. downloadElement.href = href;
  18. downloadElement.download = fileName;
  19. document.body.appendChild(downloadElement);
  20. downloadElement.click();
  21. document.body.removeChild(downloadElement);
  22. window.URL.revokeObjectURL(href);
  23. }
  24. const download = () => {
  25. // 判断querys是否是函数,函数执行函数,否则直接赋值
  26. let params = typeof querys === 'function' ? querys() : querys
  27. if (params?.date) {
  28. params['startTime'] = moment(params.date[0]).format('YYYY-MM-DD')
  29. params['endTime'] = moment(params.date[1]).format('YYYY-MM-DD')
  30. } else {
  31. delete params['startTime']
  32. delete params['endTime']
  33. }
  34. delete params['date']
  35. api.run({ ...params, pageSize: 20, pageNum: 1 }).then((res: any) => {
  36. downloadFile(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
  37. message.success("下载成功!")
  38. })
  39. }
  40. return <Button type='primary' onClick={download} loading={api?.loading}><CloudDownloadOutlined />下载Excel</Button>
  41. }
  42. export default DownloadExcel