User37
User37

Reputation: 31

Export to csv in a particular format

Is there any specific way where I can control the update of each data in a column of the csv file. I want few columns to be in text format and few in number format.

For eg:

I want to update this column with heading "Stock" and the values are :

250.000,10.000,0.000,0.000,2.500,30.000,700.000,10.000,250.000,0.000.

However the exported csv file is not taking the decimal values. It is displaying as

250,10,0,0,2.5 etc

Usually manually I can go to the csv file each column, select it, right click , format cell and then change the format to text or number. However I don't want to do it manually. I want it to be automatically done when my csv is exported. Code:

$.each(exportArray, function (index, value) {
    csvData.push(x[index] + "," + y[index] + "," + d[index] + "," + z[index]  + ","+ a[index] + "," + e[index] + "," + b[index] + "," + c[index]);
});

csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(output);

$(this)
    .attr({
        'download': filename,
        'href': csvData,
        'target': '_blank'
    });

Upvotes: 1

Views: 1531

Answers (2)

gre_gor
gre_gor

Reputation: 6803

In a CSV file, you can't define, what format a cell is.
Excel will use the default format for numbers.

If you want control over the cell format, you should use a different file format like SYLK.

Upvotes: 0

tatx
tatx

Reputation: 71

See this question and the accepted answer - Format number to always show 2 decimal places

Essentially you will need to do this:

function toFixed3(n) {
    return parseFloat(Math.round(n * 1000) / 1000).toFixed(3);
}

csvData.push(toFixed3(x[index]) + "," + toFixed3(y[index]) + "," + 
    toFixed3(d[index]) + "," + toFixed3(z[index])  + ","+ 
    toFixed3(a[index]) + "," + toFixed3(e[index]) + "," + 
    toFixed3(b[index]) + "," + toFixed3(c[index]));

Upvotes: 1

Related Questions