Vue前后分离 Laravel 如何提供导出Excel文件的接口呢?

maatwebsite/excel3.1
laravel 5.8
希望能给一个大概的思路!

附言 1  ·  4年前

谢谢各位,各位的方法都可以,问题已经解决。

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
da_house
最佳答案

首先创建一个trait

use App\Exports\TablesExport;
use Maatwebsite\Excel\Facades\Excel;

/**
 * Trait Excel导出的相关方法.
 */
trait ExcelTrait
{
    /**
     * @param $header(表头)
     * @param $list(数据)
     * @param $name(表名)
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function excelExport($header, $list, $name)
    {
        $name = $name . date('YmdHis') . '.xlsx';
        $keys = array_keys($header);
        $result[0] = $header;
        foreach ($list as $k => $v) {
            foreach ($keys as $v2) {
                if (is_array($list)) {
                    $result[$k + 1][$v2] = $v[$v2];
                } else {
                    $result[$k + 1][$v2] = $v->{$v2};
                }
            }
        }
        $result = collect($result);
        return Excel::download(new TablesExport($result), $name);
    }
}

然后 使用这个trait

 public function export(Request $request)
    {
        $list = $this->adRoot->export($request->all());
        $header = config('custom.table.admin.ads');
        return $this->excelExport($header, $list, '广告列表');
    }
header
  [
            'id' => '广告ID',
            'ad_name' => '广告名称',
            'name' => '广告主名称',
            //'user_type' => '广告主类型',
            'order_name' => '计划名称',
            'time' => '投放时间',
            'created_at' => '创建日期',
            'status' => '状态',
            'verify' => '审核状态',
        ],
如有格式问题 再给我发信息吧
4年前 评论
讨论数量: 9

导出文件即把数据库的数据写入到文件,写入完成后返回一个下载链接给前端即可,如果是用laravel可以看下下载文件,希望对你有帮助

4年前 评论

封装请求方法

export function exportCompany (parameter) {
  return axios({
    url: `/${store.getters.dashboardType}/${api.company}/export`,
    method: 'post',
    params: parameter,
    responseType: 'blob'
  })
}

实际调用

download () {
  exportCompany().then(res => {
    this.convertRes2Blob(res)
  })
},
// 文件流转换方法
convertRes2Blob (response) {
  // 提取文件名
  const fileNameList = response.headers['content-disposition'].match(
    /filename\*=(.*)''(.*)/
  )
  const fileName = fileNameList[2]

  // 将二进制流转为blob
  const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
    window.navigator.msSaveBlob(blob, decodeURI(fileName))
  } else {
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob)
    // 创建a标签,用于跳转至下载链接
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    tempLink.setAttribute('download', decodeURI(fileName))
    // 兼容:某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 挂载a标签
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL)
  }
}
4年前 评论
Hesunfly

前端进行导出请求,然后php将文件进行导出保存在磁盘中,然后给前端返回资源的地址即可

4年前 评论

vue端请求,php 端直接返回文件响应即可

4年前 评论
da_house

首先创建一个trait

use App\Exports\TablesExport;
use Maatwebsite\Excel\Facades\Excel;

/**
 * Trait Excel导出的相关方法.
 */
trait ExcelTrait
{
    /**
     * @param $header(表头)
     * @param $list(数据)
     * @param $name(表名)
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function excelExport($header, $list, $name)
    {
        $name = $name . date('YmdHis') . '.xlsx';
        $keys = array_keys($header);
        $result[0] = $header;
        foreach ($list as $k => $v) {
            foreach ($keys as $v2) {
                if (is_array($list)) {
                    $result[$k + 1][$v2] = $v[$v2];
                } else {
                    $result[$k + 1][$v2] = $v->{$v2};
                }
            }
        }
        $result = collect($result);
        return Excel::download(new TablesExport($result), $name);
    }
}

然后 使用这个trait

 public function export(Request $request)
    {
        $list = $this->adRoot->export($request->all());
        $header = config('custom.table.admin.ads');
        return $this->excelExport($header, $list, '广告列表');
    }
header
  [
            'id' => '广告ID',
            'ad_name' => '广告名称',
            'name' => '广告主名称',
            //'user_type' => '广告主类型',
            'order_name' => '计划名称',
            'time' => '投放时间',
            'created_at' => '创建日期',
            'status' => '状态',
            'verify' => '审核状态',
        ],
如有格式问题 再给我发信息吧
4年前 评论

如果没有跨域问题的话,直接返回文件的地址给前端,让他们直接用a标签,进行下载就好。

4年前 评论

前端是可以直接导出csv文件的,直接取table的数据,不需要后端另外写功能

4年前 评论

这种的前端导出, 后台用的element UI

    onExport() {
      this.$message.info('正在导出...')
      this.query.export = 1
      let query = "?"
      for (const key in this.query) {
        if (this.query.hasOwnProperty(key)) {
          query += key + "=" + this.query[key] + "&"
        }
      }
      query += 'admin_token='+ getToken()
      window.location.href = process.env.VUE_APP_BASE_API + "/admin/order/list" + query
  }
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!