3

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

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){

}

service is like this

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

view

    <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 enter image description here

Daniel
  • 10,641
  • 12
  • 47
  • 85
sooraj s pillai
  • 866
  • 2
  • 17
  • 39
  • If you want to create CSV file from response data then [go for this comment](https://stackoverflow.com/questions/20300547/download-csv-file-from-web-api-in-angular-js/64315710#64315710) – Tejashree Oct 12 '20 at 10:08

3 Answers3

3

You need to navigate the browser to the route where the Excel file is made on the backend (in a new tab) either with a link <a href="path" target="_blank"> or with window.open

The ->download() function sets headers so that the file will be automatically downloaded.

When you fetch this data with an AJAX call (which is what HttpClient does) you simply get the binary data returned (which is what you see in your Response tab in Chrome developer tools).

(There are front-end hacks to download a file retrieved by ajax such as creating a link element and clicking it with JavaScript (see below), but they can not be recommended):

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

a.href = window.URL.createObjectUrl(responseData);
a.download = fileName;
a.click();
Daniel
  • 10,641
  • 12
  • 47
  • 85
1

This can also be done using file-saver:

import * as FileSaver from 'file-saver';

this.http.post(`${this.baseUrl}downloadExcel`, data, { responseType: 'blob' })
 .subscribe((resp: any) => {
    saveAs(resp, `filename.csv`)
 });
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
  • https://stackoverflow.com/questions/20300547/download-csv-file-from-web-api-in-angular-js/64315710#64315710 If you want to create csv file from data. – Tejashree Oct 12 '20 at 10:09
0

This function working for me to export 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();
}
Swatantra Kumar
  • 1,324
  • 5
  • 24
  • 32
Gustavo Marquez
  • 419
  • 4
  • 6