Avoid stripping leading zeros while copying data to csv : Angular 8

Viewed 495

I am trying to download data in .csv. In some of the values in the JSON object has multiple values like "000". When this is being downloaded in CSV(excel) then "000" has been trimmed to "0". I am using following JS : import { saveAs } from 'file-saver'

 BindTable(dt, ID) {
    this.dtRequests = [];     
    this.dtRequests = JSON.parse(json);
    const replacer = (key, value) => value === null ? '' : value ;
    let DownldData: any;
    let fileName = ID+ '_RInfo.csv';
    DownldData = this.dtRequests;
    const header = Object.keys(DownldData[0]);
    let csv = DownldData.map(row => header.map(fieldName => JSON.stringify(row[fieldName], 
    replacer)).join(','));
    csv.unshift(header.join(','));
    let csvArray = csv.join('\r\n');
    var blob = new Blob([csvArray], { type: 'text/csv' });
    saveAs(blob, fileName);
  }

I have tried the following things and it didn't work.

const replacer = (key, value) => value === null ? '' : '\t' + String(value) ; // Output "\t000"
const replacer = (key, value) => value === null ? '' : '' + String(value) ; // Output "0"
const replacer = (key, value) => value === null ? '' : "''" + String(value) + "''"; // Output "000"

Is there any better way to handle in angular 8?

1 Answers

var test = "000456"; var insertValueAs = "\t" + test;

working perfectly in angular11- code tested

Related