Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 760
CuriousJ Avatar asked Jun 02 '26 07:06

CuriousJ


1 Answers

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

working perfectly in angular11- code tested

like image 185
kiran reddy Avatar answered Jun 03 '26 21:06

kiran reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!