8891/laravel-exportcsv

通过中间件导出 CSV,无需修改源代码,只需使用 composer require

安装次数: 1

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

开放问题: 0

类型:laravel-扩展

dev-master 2019-02-28 01:01 UTC

This package is auto-updated.

Last update: 2024-09-28 13:19:58 UTC


README

ExportCsv 解决 csv 统一下载导出的功能

  • 客户端通过设置 Accept: text/csv 头部来触发下载
  • 支持大文件串流下载,解决内存超出问题
  • 下载的 csv 文件可以直接通过 Excel 打开,无需导入
  • 基于 league/csv 包实现 csv 导出
  • 提供 exporting (正在导出) 和 exported (已导出) 事件,方便在导出前后进行处理。例如,审计
  • 默认注入到 web 和 api 两组路由中,并删除 pagepagesize 两个请求参数

需求

  • PHP 7+
  • Laravel 5.6+

用法

服务器

只需要 require 进来就可以,无需任何配置

composer require 8891/laravel-exportcsv

客户端

通过 fetch 异步下载

const downloadIfAttachment = response => {
  let contentDisposition = response.headers.get('Content-Disposition') || '';
  if (contentDisposition.toLowerCase().includes('attachment')) {
    let filename = contentDisposition.split('=').map(v => v.trim())[1];
    response.blob().then( blob => {
        let a = document.createElement("a"),
          url = URL.createObjectURL(blob);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    });
    return false;
  }
  
  return response;
}

fetch(url, {
    headers: {
        'Accept': 'text/csv'
    }
})
// content-disposition: attachment; filename=data.csv
.then(downloadIfAttachment)
.then(response => {
    // do something
});

待办事项

  • 增加通过参数指定 export=csv 触发下载
  • 增加配置自定义排除的请求参数
  • 增加判断 response 是 json 或 array 才能通过 csv 下载,否则报错