vue使用xlsx封装excel导入、导出组件

294 阅读1分钟

导入excel

[参考链接](Import Tutorial | SheetJS Community Edition)

<template>
  <el-button @click="onUpload">上传</el-button>
  <input ref="uploadRef" type="file" @change="beforeUpload" accept=".xlsx, .xls" hidden>
</template>

<script setup lang="ts">
import * as XLSX from 'xlsx';
import { ref } from 'vue'

const emits = defineEmits<{
  (e: 'importList', data: Array<object>): void
}>()

//导入
const uploadRef = ref()
const onUpload = () => {
  uploadRef.value.click()
}
const importList = ref<any>([]);
const beforeUpload = async (e: any) => {
  importList.value = await analysisExcel(e.target.files[0]);
  handleMany()
}
const analysisExcel = (file: any) => {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader();
    reader.onload = function (e: any) {
      const data = e.target.result;
      let datajson = XLSX.read(data, {
        type: 'binary',
      });

      const sheetName = datajson.SheetNames[0];
      const result = XLSX.utils.sheet_to_json(datajson.Sheets[sheetName]);
      resolve(result);
    };
    reader.readAsBinaryString(file);
  });
}
const handleMany = async () => {
  // 把数据传给服务器后获取最新列表,这里只是示例,不做请求
  //处理数据
  //添加到表格
  emits('importList', importList.value)

};
</script>

<style scoped></style>

导出excel

[参考链接](Export Tutorial | SheetJS Community Edition)

<template>
  <el-button type="primary" @click="exportXlsx">导出Excel</el-button>
</template>

<script setup lang="ts" name="export">
import * as XLSX from 'xlsx';

const props = withDefaults(defineProps<{
  tableData: Array<object>,
  tableTitle: Array<string>,
  fileName?: string
}>(), {
  fileName: '表格'
})

const exportXlsx = () => {
  const keys: (string | number)[] = Object.keys(props.tableData[0])
  const list: string[][] = [props.tableTitle]

  props.tableData.map((item: object) => {
    const arr: string[] = []
    keys.map((k) => {
      arr.push(item[k])
    })
    list.push(arr)
  })

  let WorkSheet = XLSX.utils.aoa_to_sheet(list as any);
  let new_workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(new_workbook, WorkSheet, '第一页');
  XLSX.writeFile(new_workbook, `${props.fileName}.xlsx`);
};
</script>