3
votes

Téléchargement CSV angulaire 6

Je suis nouveau dans angular, actuellement je travaille dans un projet qui nécessite une exportation csv. Ici, j'utilise Angular 6 comme frontend et laravel comme backend

Voici comment j'ai écrit la fonction laravel en utilisant mattwebsite / excel

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

Voici comment j'ai écrit la fonction en angular composant

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

le service est comme ceci

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

}

vue

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

en faisant cela, j'obtiens une réponse comme celle-ci mais le fichier ne se télécharge pas entrez la description de l'image ici


1 commentaires

Si vous souhaitez créer un fichier CSV à partir des données de réponse, allez pour ce commentaire


3 Réponses :



1
votes

Cela peut également être fait en utilisant file-saver :

importer * en tant que FileSaver depuis 'file-saver';

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


1 commentaires

stackoverflow.com/questions/20300547/... Si vous souhaitez créer un fichier csv à partir de données.



0
votes

Cette fonction fonctionne pour moi pour exporter 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();
}


0 commentaires