Front-end export to excel (common to Vue and React)

Note: This is the conversion of pure front-end data processing to excel. Under normal circumstances, it is necessary to After the file stream is generated on the end, we export it.

Go directly to the code:

vue: First introduce XLSX in the script tag

react: directly introduce XLSX into the folder of the current page

import XLSX from 'xlsx'

Please note that you need to install the XLSX library in your project before using this method. You can install the XLSX library through npm with the following command:

npm install xlsx --save

Define this method in js:

// 导出excel
exportData() {
  // 这里的this.dataExport表示要导出的数组数据(vue的写法)如果是react,只需把data赋值成要导出的数据的值就行。注意数据必须是数组类型
  const data = this.dataExport
  // 创建一个Excel文件对象
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(data);
  console.log("workbook",workbook);
  console.log("worksheet",worksheet);
  // 将worksheet添加到workbook中
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  // 将workbook转换为blob对象
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([wbout], { type: 'application/octet-stream' });
  // 下载Excel文件
  const fileName = '导出表格详情表.xlsx';
  if ('download' in document.createElement('a')) {
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
  } else {
    navigator.msSaveBlob(blob, fileName);
  }
}

Executing this method in the click event can realize table export~

This is the most basic form export. If you have any questions, you can ask them below! Bloggers will reply when they see it

Guess you like

Origin blog.csdn.net/weixin_73318685/article/details/131781800