目的:前端导入表格

使用xlsx的包 版本是 0.16.8 最新的目前是18 不兼容 有问题

import * as XLSX from 'xlsx';
// import XLSX from 'xlsx' 没有这样写 是因为报错了 有知道为什么的可以评论一下 共享
function getHeaderRow(sheet) {
  const headers = []
  const range = XLSX.utils.decode_range(sheet['!ref'])
  let C
  const R = range.s.r
  /* start in the first row */
  for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
    const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
    /* find the cell in the first row */
    let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
    if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
    headers.push(hdr)
  }
  return headers
}
// 读取Excel文件数据
export function readExcelFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = e.target.result
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const header = getHeaderRow(worksheet)
      const results = XLSX.utils.sheet_to_json(worksheet)
      resolve({ header, results })
    };
    reader.onerror = (e) => {
      reject(e);
    };
    reader.readAsArrayBuffer(file);
  });
}
// 会返回表头数组 和 结果数组   fileValue = e.target.files[0] 我用的<input type="file" 原生
const { header = [], results = [] } = await readExcelFile(fileValue)
// results返回的键是中文的 需要转成英文 变成表格需要的数据 
  const chineseMap = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
   const importData = results.map(item => {
              const itemObj = {}
              Object.keys(item).forEach(key => {
                itemObj[chineseMap[key]] = String(item[key]).trim()
              })
              return itemObj
            })

导出--我这里的导出只是element-ui里面的普通表格 数据也没有合并的地方等等

   引用自 xlsx库实现纯前端导入导出Excel

import * as XLSX from 'xlsx'; // import XLSX from 'xlsx'; 这样会报错
/**
 * 将 table 转换成 Excel 导出
 * @param {*} el table 的根 dom 元素
 * @param {*} fileName 下载时文件名称
 */
export const exportExcelByTable = (el, fileName = 'example.xlsx') => {
  if (!el) {
    throw new Error('没有获取到表格的根 dom 元素');
  }
  const options = { raw: true };
  const workbook = XLSX.utils.table_to_book(el, options);
  return XLSX.writeFile(workbook, fileName, { type: 'binary' });
};


 handleTableExport() {
    const el = this.$refs.tableRef.$el
      exportExcelByTable(el)
    },

二.上面的是vue2的  下面是v3的导出table表格

// 需要自己看一下自己用的是a-table还是el-table 对应的列方法不一样
// 我拿a-table举例
// 首先 npm install file-saver xlsx --save
<a-button type="primary" @click="exportToExcel">导出</a-button>
<a-table :columns="tableColumns" :pagination="false" :dataSource="tableDataSource"                                                      ref="tableRef">
</a-table>
<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue'
  import FileSaver from 'file-saver'
  import * as XLSX from 'xlsx'
  const tableRef = ref()
  const tableColumns = ref([
    {
      title: '序号',
      dataIndex: 'xuIndex'
    },
    {
      title: '姓名',
      dataIndex: 'personName'
    },

    {
      title: '工号',
      dataIndex: 'jobNo'
    },
    {
      title: '卡号',
      dataIndex: 'cardNo'
    },
    {
      title: '所属组织',
      dataIndex: 'orgName'
    },
    {
      title: '门禁点',
      dataIndex: 'doorName'
    },
    {
      title: '控制器名称',
      dataIndex: 'devName'
    },
    {
      title: '事件类型',
      dataIndex: 'eventTypeName'
    },
    {
      title: '事件产生时间',
      dataIndex: 'eventTime'
    }
  ])
  const tableDataSource = ref([])
// 下面那两个是导出table表格的方法
 const resetTableData = () => {
// el-table是这个地方 tableColumns.value.map((item) => [item.prop, item.label]))别的都一样
    const propToLabelMap = new Map(tableColumns.value.map((item) => [item.dataIndex, item.title]))
    const restructuredTableData = []
    tableDataSource.value.map((row) => {
      // 使用映射表创建新对象,其中键为label值,值为原对象的相应prop值
      const newRow = {}
      for (const prop in row) {
        if (row.hasOwnProperty(prop) && propToLabelMap.has(prop)) {
          newRow[propToLabelMap.get(prop)] = row[prop]
        }
      }
      restructuredTableData.push(newRow)
    })
    return restructuredTableData
  }
  const exportToExcel = () => {
    console.log(resetTableData())
    let newTableData = resetTableData()
    // 假设 this.tableData 是你的表格数据,每一项是一个对象,对应表格的一行
    //处理表格数据得到数据
    const worksheet = XLSX.utils.json_to_sheet(newTableData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

    const excelBuffer = XLSX.write(workbook, {
      bookType: 'xlsx',
      type: 'array'
    })
    // 将缓冲区转换为 Blob 并保存为文件
    const data = new Blob([excelBuffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    FileSaver.saveAs(data, 'tableData.xlsx')
  }
</script>

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐