【问题标题】:Angular 6 CSV download角 6 CSV 下载
【发布时间】:2019-09-10 07:35:09
【问题描述】:

我是 Angular 的新手,目前我正在从事一个需要 csv 导出的项目。这里我使用 Angular 6 作为前端,使用 laravel 作为后端

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

// 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);
}

这就是我在角度组件中编写函数的方式

    // 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>

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

【问题讨论】:

标签: php angular laravel-5 maatwebsite-excel


【解决方案1】:

您需要使用链接&lt;a href="path" target="_blank"&gt; 或window.open 将浏览器导航到在后端(在新选项卡中)创建 Excel 文件的路径

-&gt;download() 函数设置标题以便自动下载文件。

当您通过 AJAX 调用(HttpClient 所做的)获取此数据时,您只需获取返回的二进制数据(您在 Chrome 开发人员工具的“响应”选项卡中看到的内容)。

(有一些前端黑客可以下载通过 ajax 检索的文件,例如创建链接元素并使用 JavaScript 进行单击(见下文),但不推荐使用它们): p>

let fileName = 'filename.xlsx';
let a = document.createElement('a');

a.href = window.URL.createObjectUrl(responseData);
a.download = fileName;
a.click();

【讨论】:

    【解决方案2】:

    这也可以使用file-saver:

    import * as FileSaver from 'file-saver';

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

    【讨论】:

    【解决方案3】:

    这个功能对我有用,可以导出 csv,

    downloadFile(data: any) {
        const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
        const header = Object.keys(data[0]);
        let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
        csv.unshift(header.join(','));
        let csvArray = csv.join('\r\n');
    
        var a = document.createElement('a');
        var blob = new Blob([csvArray], {type: 'text/csv' }),
        url = window.URL.createObjectURL(blob);
    
        a.href = url;
        a.download = "myFile.csv";
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2016-06-23
      相关资源
      最近更新 更多