exportCsv.ts 1.9 KB

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