DEV Community

Discussion on: Exporting Data To Excel and CSV in Angular

Collapse
 
idrisrampurawala profile image
Idris Rampurawala

Hey, you can find the same in the export.service.ts

   // check out this line
    XLSX.utils.book_append_sheet(workbook, ws, 'Sheet1');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hshahul profile image
hshahul

This one for export excel right? not for export CSV? Please check and let me sample example where I need to add this code in the following code if it is correct...

private saveAsFile(buffer: any, fileName: string, fileType: string): void {
const data: Blob = new Blob([buffer], { type: fileType });
FileSaver.saveAs(data, fileName);
}

/**

  • Creates an array of data to csv. It will automatically generate title row based on object keys. *
  • @param rows array of data to be converted to CSV.
  • @param fileName filename to save as.
  • @param columns array of object properties to convert to CSV. If skipped, then all object properties will be used for CSV. */ public exportToCsv(rows: object[], fileName: string, columns?: string[]): string { if (!rows || !rows.length) { return; } const separator = ','; const keys = Object.keys(rows[0]).filter(k => { if (columns?.length) { return columns.includes(k); } else { return true; } }); const csvContent = keys.join(separator) + '\n' + rows.map(row => { return keys.map(k => { let cell = row[k] === null || row[k] === undefined ? '' : row[k]; cell = cell instanceof Date ? cell.toLocaleString() : cell.toString().replace(/"/g, '""'); if (cell.search(/("|,|\n)/g) >= 0) { cell = "${cell}"; } return cell; }).join(separator); }).join('\n'); this.saveAsFile(csvContent, ${fileName}${CSV_EXTENSION}, CSV_TYPE); } }

I want to give different name for file and tab in CSV.

Thread Thread
 
idrisrampurawala profile image
Idris Rampurawala

You can pass the filename as mentioned in the function's exportToCsv dosctring. Also, CSV's won't have sheets in it ;)