exportCsv.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import type { StdTableProps } from '@/components/StdDesign/StdDataDisplay/StdTable.vue'
  2. import type { Column, StdTableResponse } from '@/components/StdDesign/types'
  3. import type { ComputedRef } from 'vue'
  4. import { downloadCsv } from '@/lib/helper'
  5. import { message } from 'ant-design-vue'
  6. import dayjs from 'dayjs'
  7. import _ from 'lodash'
  8. async function exportCsv(props: StdTableProps, pithyColumns: ComputedRef<Column[]>) {
  9. const header: { title?: string, key: Column['dataIndex'] }[] = []
  10. // eslint-disable-next-line ts/no-explicit-any
  11. const headerKeys: any[] = []
  12. const showColumnsMap: Record<string, Column> = {}
  13. pithyColumns.value.forEach((column: Column) => {
  14. if (column.dataIndex === 'action')
  15. return
  16. let t = column.title
  17. if (typeof t === 'function')
  18. t = t()
  19. header.push({
  20. title: t,
  21. key: column.dataIndex,
  22. })
  23. headerKeys.push(column?.dataIndex?.toString())
  24. showColumnsMap[column?.dataIndex?.toString() as string] = column
  25. })
  26. // eslint-disable-next-line ts/no-explicit-any
  27. const dataSource: any[] = []
  28. let hasMore = true
  29. let page = 1
  30. while (hasMore) {
  31. // 准备 DataSource
  32. await props
  33. .api!.get_list({ page }).then((r: StdTableResponse) => {
  34. if (r.data.length === 0) {
  35. hasMore = false
  36. return
  37. }
  38. dataSource.push(...r.data)
  39. }).catch((e: { message?: string }) => {
  40. message.error(e.message ?? $gettext('Server error'))
  41. hasMore = false
  42. })
  43. page += 1
  44. }
  45. // eslint-disable-next-line ts/no-explicit-any
  46. const data: any[] = []
  47. dataSource.forEach(row => {
  48. // eslint-disable-next-line ts/no-explicit-any
  49. const obj: Record<string, any> = {}
  50. headerKeys.forEach(key => {
  51. let _data = _.get(row, key)
  52. const c = showColumnsMap[key]
  53. _data = c?.customRender?.({ text: _data }) ?? _data
  54. _.set(obj, c.dataIndex as string, _data)
  55. })
  56. data.push(obj)
  57. })
  58. downloadCsv(header, data, `${$gettext('Export')}-${props.title}-${dayjs().format('YYYYMMDDHHmmss')}.csv`)
  59. }
  60. export default exportCsv