I want to get a csv file downloaded with the white spaces preserved in between the words.
HTML
<select id="ddl">
<option value="1">One apple</option>
<option value="2">Two Oranges</option>
<option value="3">Three Grapes</option>
</select>
JAVASCRIPT
var ddlArray= new Array();
var ddl = document.getElementById('ddl');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl .options[i].text;
}
var csvRows = [];
for (i = 0; i < ddlArray.length; i++) {
csvRows.push(ddlArray[i]+",");
}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + csvString;
a.target = '_blank';
a.download = 'sampleDownload.csv';
document.body.appendChild(a);
a.click();
When I am executing the above code, a sampleDownload.csv is getting downloaded, but the option values are getting trimmed so that all the white spaces are lost. Example "OneApple" instead of "One Apple". Will it be possible to preserve the white spaces in the csv file?
If I execute an alert the value do contain the white space.
Please help.
The snippet can also be found in JSFiddle: Click here: http://jsfiddle.net/p25x8gfw/8/
This will download a samleDownload.csv on your machine. Works in Chrome and Firefox.
Try This...
var ddlArray= new Array();
var ddl = document.getElementById('ddl');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl .options[i].text.replace(' ', '%20');
}
var csvRows = [];
for (i = 0; i < ddlArray.length; i++) {
csvRows.push(ddlArray[i].replace(' ', '%20')+",");}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + csvString;
a.target = '_blank';
a.download = 'sampleDownload.csv';
document.body.appendChild(a);
a.click();
Here csv file consider %20 is whitespace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With