纯原生JS实现导出Excel文件

前言:

  1. 各种js库用起来冗余,并且只想简单的导出excel文件
  2. 选择table标签是为了后期能定制化内容

0、效果预览

excel文件:

image-20230504173114035

浏览器控制台

image-20230504173338415

触发下载:

image-20230504173032895

1、定义工具函数:

// xlsxExport.js
/**
 *纯前端 原生导出excel
 */

const trans2Base64 = (content) => {
  return window.btoa(unescape(encodeURIComponent(content)));
};

export const exportExcelFromFront = (params) => {
  const { cellList, headerList, caption, exportName = 'exportName' } = params;

  const captionEle = caption ? `<caption>${caption}</caption>` : ''; // 表格标题
  const headerEle = `<tr>${headerList?.map((item) => `<th>${item}</th>`)?.join('')}</tr>`;
  const cellEle = cellList
    ?.map((itemRow) => `<tr>${itemRow?.map((itemCell) => `<td>${itemCell}</td>`)?.join('')}</tr>`)
    ?.join('');

  const excelContent = `${captionEle}${headerEle}${cellEle}`;
  let excelFile =
    "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
  excelFile +=
    '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
  excelFile += "<body><table width='10%'  border='1'>";
  excelFile += excelContent;
  excelFile += '</table></body>';
  excelFile += '</html>';
  const link = `data:application/vnd.ms-excel;base64,${trans2Base64(excelFile)}`;
  const a = document.createElement('a');
  a.download = `${exportName}.xlsx`;
  a.href = link;
  a.click();
};

2、调用函数

// 根据自己的实际目录去调
import { exportExcelFromFront } from '@/utils/xlsxExport';

const handleExport = () => {
    const caption="我是heander标题"
    const headerList = ['标题1','标题2','标题3'];
    const cellList = [
      ['内容1','内容2','内容3'],
      ['内容4','内容5','内容6'],
      ['内容7','内容8','内容9'],
    ];
  	const exportName='导出的文件名称'

    const params = {
      caption,
      headerList,
      cellList,
      exportName,
    };
    exportExcelFromFront(params);
  };

================
over了

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值