前端导出Excel实践:探索xlsl的实现方式

点击在线阅读,体验更好 链接
现代JavaScript高级小册 链接
深入浅出Dart 链接
现代TypeScript高级小册 链接
linwu的算法笔记 链接

前言

最近写管理端的需求,发现有一个excel导出的需求,本来是后端同学负责,但是因为他们太忙了,把这块任务交给前端了,起初产品觉得前端实现不了,一听这话,这我哪里受得了,赶紧写了个demo给她看,前端是可以实现的。enen,产品看了直夸牛逼

接下来,我来分享导出excel文件的三种实现方式

url下载

在这种方式中,我们的目标是后端生成Excel文件并提供一个地址,前端通过访问这个地址来下载导出的Excel文件。

// 后端接口:/api/export/excel
// 请求方式:GET
// 假设后端接口返回导出地址的数据格式为 { url: "https://example.com/excel_exports/exported_file.xlsx" }

export const exportExcelViaURL = () => {
   
  // 发起后端接口请求获取导出地址
  fetch('/api/export/excel')
    .then((response) => response.json())
    .then((data) => {
   
      const {
    url } = data;
      // 创建一个隐藏的标签并设置href属性为后端返回的地址
      const link = document.createElement('a');
      link.href = url;
      link.target = '_blank';
      link.download = `exported_data_${
     dayjs().format('YYYY-MM-DD_hh.mm.ss_a')}.xlsx`;
      // 触发点击操作,开始下载文件
      link.click();
    })
    .catch((error) => {
   
      console.error('导出Excel失败:', error);
    });
};

Blob文件流

后端直接返回Blob文件流数据,前端通过接收到的Blob数据进行文件下载。

// 后端接口:/api/export/excel/blob
// 请求方式:GET

export const exportExcelViaBlob = () => {
   
  // 发起后端接口请求获取Blob文件流数据
  fetch('/api/export/excel/blob')
    .then((response) => response.blob())
    .then((blobData) => {
   
      // 创建Blob URL
      const blobUrl = URL.createObjectURL(blobData);
      // 创建一个隐藏的标签并设置href属性为Blob URL
      const link = document.createElement('a'

你可能感兴趣的:(前端,excel,状态模式,javascript,ecmascript,typescript)