[Fixed] How to export Angular Table to csv in Angular 10


I have a table that I generate from BLOB html stored in a database. I have managed to export the table generated to excel and pdf, now I need the same table in csv. Have tried to research but all am getting is passing json and generating the csv, but I want to just pass the table ID and export to CSV.

What I have done for excel.

 exportexcel(): void {
    /* table id is passed over here */
    let element = document.getElementById('htmlData');
    const ws: XLSX.WorkSheet =XLSX.utils.table_to_sheet(element);

    /* generate workbook and add the worksheet */
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    XLSX.writeFile(wb, this.fileName);


How can I achieve the same by passing let element = document.getElementById('htmlData'); and export it to csv. I don’t want to go through the option of mat-table-exporter. Thank you in advance


May be following code would be helpful for you!

 exportcsv(): void {
    let csv='';
    let table=document.getElementById("htmlData");
    let tr=table.children[0].children[0];
    for(let i=0;i<tr.children.length;i++)
    let tbody=table.children[1];
    for(let i=0;i<tbody.children.length;i++)
        for(let j=0;j<tbody.children[i].children.length;j++)
        let hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'data.csv';

Leave a Reply

(*) Required, Your email will not be published