Angular 6 CSV下载 [英] Angular 6 CSV download

查看:315
本文介绍了Angular 6 CSV下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular的新手,目前我正在一个需要csv导出的项目中工作.在这里,我将Angular 6用作前端,将laravel用作后端

I'm new to angular, currently i'm working in a project which needs an csv export. Here i'm using Angular 6 as frontend and laravel as backend

这就是我使用mattwebsite/excel编写laravel函数的方式

This is how i wrote laravel function using mattwebsite/excel

// Lead export to csv
public function downloadExcel(Request $request)
{
    $credentials = $request->only('token');
    $token = $credentials['token'];
    $userid = $this->getUseridFromToken($token);
    $type = "xls";
    $data = DB::table('user_mailbox AS A')
                    ->select('A.id', 'A.name', 'A.email', 'A.phone', DB::raw('DATE_FORMAT(A.send_on, "%d / %b / %Y") as send_on'), 'B.listing_heading','B.listing_id','B.listing_heading', 'C.name')
                    ->leftjoin('broker_listing AS B', 'B.listing_id', '=', 'A.listing_id')
                    ->leftjoin('users AS C', 'C.id', '=', 'A.sent_by')
                    ->where('A.sent_to', $userid)
                    ->where('A.user_type', '1')
                    ->orderBy('A.id', 'desc')->get()->toArray(); 
    Excel::create('Lead_Export', function($excel) use ($data) {
        $excel->sheet('Lead_Export', function($sheet) use ($data)
        {
            $sheet->fromArray($data);
        });
    })->download($type);
}

这就是我在角度分量中编写函数的方式

This is how i wrote function in angular component

    // Download leads as excel
download_excel(){
  const fd = new FormData(); 
  fd.append('token',this.token);
  this.brokerleads.downloadLeads(fd).subscribe(
    data => this.handleResponsedwnload(data),
    error => this.handleErrordwnload(error)
  );
}
handleResponsedwnload(data){ console.log('test');
  const blob = new Blob([data], { type: 'text/xls' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}
handleErrordwnload(data){

}

服务就是这样

  // Download as excel
  downloadLeads(data):Observable<any>{
    return this.http.post(`${this.baseUrl}downloadExcel`, data);   
  }

查看

    <a class="export-leads" href="javascript:void(0);" (click)="download_excel()" >EXPORT LEADS</a>

在执行此操作时,我得到了这样的响应,但文件未下载

while doing this i'm getting response like this but file is not downloading

推荐答案

这也可以使用文件保护程序:

import * as FileSaver from 'file-saver';

this.http.post(`${this.baseUrl}downloadExcel`, data, { responseType: 'blob' })
 .subscribe((resp: any) => {
    saveAs(resp, `filename.csv`)
 });

这篇关于Angular 6 CSV下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆