index.vue 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <template>
  2. <div ref="xspreadsheet" class="xspreadsheet" :class="{'xspreadsheet-readonly':readOnly}"></div>
  3. </template>
  4. <style lang="scss">
  5. .xspreadsheet-readonly {
  6. .x-spreadsheet-menu {
  7. > li:first-child {
  8. > div.x-spreadsheet-icon {
  9. display: none;
  10. }
  11. }
  12. }
  13. }
  14. </style>
  15. <style lang="scss" scoped>
  16. .xspreadsheet {
  17. position: absolute;
  18. top: 0;
  19. left: 0;
  20. width: 100%;
  21. height: 100%;
  22. display: flex;
  23. }
  24. </style>
  25. <script>
  26. import Spreadsheet from 'x-data-spreadsheet';
  27. import zhCN from 'x-data-spreadsheet/dist/locale/zh-cn';
  28. import XLSX from 'xlsx';
  29. export default {
  30. name: "Sheet",
  31. props: {
  32. value: {
  33. type: Object,
  34. default: function () {
  35. return {}
  36. }
  37. },
  38. readOnly: {
  39. type: Boolean,
  40. default: false
  41. },
  42. },
  43. data() {
  44. return {
  45. sheet: null,
  46. clientHeight: 0,
  47. clientWidth: 0,
  48. }
  49. },
  50. mounted() {
  51. Spreadsheet.locale('zh-cn', zhCN);
  52. //
  53. let options = {
  54. view: {
  55. height: () => {
  56. try {
  57. return this.clientHeight = this.$refs.xspreadsheet.clientHeight;
  58. }catch (e) {
  59. return this.clientHeight;
  60. }
  61. },
  62. width: () => {
  63. try {
  64. return this.clientWidth = this.$refs.xspreadsheet.clientWidth;
  65. }catch (e) {
  66. return this.clientWidth;
  67. }
  68. },
  69. },
  70. };
  71. if (this.readOnly) {
  72. options.mode = 'read'
  73. options.showToolbar = false
  74. options.showContextmenu = false;
  75. }
  76. this.sheet = new Spreadsheet(this.$refs.xspreadsheet, options).loadData(this.value).change(data => {
  77. if (!this.readOnly) {
  78. this.$emit('input', data);
  79. }
  80. });
  81. //
  82. this.sheet.validate()
  83. },
  84. methods: {
  85. exportExcel(name, bookType){
  86. var new_wb = this.xtos(this.sheet.getData());
  87. XLSX.writeFile(new_wb, name + "." + (bookType == 'xlml' ? 'xls' : bookType), {
  88. bookType: bookType || "xlsx"
  89. });
  90. },
  91. xtos(sdata) {
  92. var out = XLSX.utils.book_new();
  93. sdata.forEach(function(xws) {
  94. var aoa = [[]];
  95. var rowobj = xws.rows;
  96. for(var ri = 0; ri < rowobj.len; ++ri) {
  97. var row = rowobj[ri];
  98. if(!row) continue;
  99. aoa[ri] = [];
  100. Object.keys(row.cells).forEach(function(k) {
  101. var idx = +k;
  102. if(isNaN(idx)) return;
  103. aoa[ri][idx] = row.cells[k].text;
  104. });
  105. }
  106. var ws = XLSX.utils.aoa_to_sheet(aoa);
  107. XLSX.utils.book_append_sheet(out, ws, xws.name);
  108. });
  109. return out;
  110. },
  111. }
  112. }
  113. </script>