execl.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <script setup lang="ts">
  2. import { utils, writeFile } from "xlsx";
  3. defineOptions({
  4. name: "Excel"
  5. });
  6. interface DataItem {
  7. readonly id: string;
  8. [propName: string]: string;
  9. }
  10. interface Columns {
  11. dataKey: string;
  12. key: string;
  13. title: string;
  14. width?: number;
  15. [propName: string]: string | number;
  16. }
  17. const generateColumns = (length = 10, prefix = "column-", props?: any) =>
  18. Array.from({ length }).map((_, columnIndex) => ({
  19. ...props,
  20. key: `${prefix}${columnIndex}`,
  21. dataKey: `${prefix}${columnIndex}`,
  22. title: `Column ${columnIndex}`,
  23. width: 150
  24. }));
  25. const generateData = (
  26. columns: ReturnType<typeof generateColumns>,
  27. length = 200,
  28. prefix = "row-"
  29. ) =>
  30. Array.from({ length }).map((_, rowIndex) => {
  31. return columns.reduce(
  32. (rowData, column, columnIndex) => {
  33. rowData[column.dataKey] = `Row ${rowIndex} - Col ${columnIndex}`;
  34. return rowData;
  35. },
  36. {
  37. id: `${prefix}${rowIndex}`,
  38. parentId: null
  39. }
  40. );
  41. });
  42. const columns = generateColumns(10);
  43. const data = generateData(columns, 1000);
  44. const exportExcel = () => {
  45. const res: string[][] = data.map((item: DataItem) => {
  46. const arr = [];
  47. columns.forEach((column: Columns) => {
  48. arr.push(item[column.dataKey]);
  49. });
  50. return arr;
  51. });
  52. const titleList: string[] = [];
  53. columns.forEach((column: Columns) => {
  54. titleList.push(column.title);
  55. });
  56. res.unshift(titleList);
  57. const workSheet = utils.aoa_to_sheet(res);
  58. const workBook = utils.book_new();
  59. utils.book_append_sheet(workBook, workSheet, "数据报表");
  60. writeFile(workBook, "tableV2.xlsx");
  61. };
  62. </script>
  63. <template>
  64. <el-card>
  65. <template #header>
  66. <div class="font-medium">
  67. 导出Execl(
  68. <el-link
  69. href="https://github.com/SheetJS/sheetjs"
  70. target="_blank"
  71. style="font-size: 16px; margin: 0 5px 4px 0"
  72. >
  73. github地址
  74. </el-link>
  75. </div>
  76. </template>
  77. <el-button type="primary" @click="exportExcel">导出Excel</el-button>
  78. <div class="h-[25rem] mt-3">
  79. <el-auto-resizer>
  80. <template #default="{ height, width }">
  81. <el-table-v2
  82. :columns="columns"
  83. :data="data"
  84. :width="width"
  85. :height="height"
  86. fixed
  87. />
  88. </template>
  89. </el-auto-resizer>
  90. </div>
  91. </el-card>
  92. </template>