excel.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 shadow="never">
  65. <template #header>
  66. <div class="font-medium">
  67. <el-link
  68. href="https://github.com/SheetJS/sheetjs"
  69. target="_blank"
  70. style="margin: 0 5px 4px 0; font-size: 16px"
  71. >
  72. 导出Excel
  73. </el-link>
  74. </div>
  75. <el-link
  76. class="mt-2"
  77. href="https://github.com/pure-admin/vue-pure-admin/blob/main/src/views/able/excel.vue"
  78. target="_blank"
  79. >
  80. 代码位置 src/views/able/excel.vue
  81. </el-link>
  82. </template>
  83. <el-button type="primary" @click="exportExcel">导出Excel</el-button>
  84. <div class="h-[25rem] mt-3">
  85. <el-auto-resizer>
  86. <template #default="{ height, width }">
  87. <el-table-v2
  88. :columns="columns"
  89. :data="data"
  90. :width="width"
  91. :height="height"
  92. fixed
  93. />
  94. </template>
  95. </el-auto-resizer>
  96. </div>
  97. </el-card>
  98. </template>