1

I was wondering whether HTML5 allows one to save/write to a local file within the user's file system. I'm asking this as I know that with HTML5 you can now export data from client and download it as a CSV file for example.

If not with HTML5, what would be the best approach to overwrite the contents, or create a CSV (or any other type of file for that matter) locally from within the client-side script?

1

2 Answers 2

11

Function:

function exportData() {
    var data = '';
    for (var i=1;i<=2;i++) {
        var sep = '';
        for (var j=1;j<=4;j++) {
            data +=  sep + document.getElementById(i + '_' + j).value;
            sep = ',';
        }
        data += '\r\n';
    }
    var exportLink = document.createElement('a');
    exportLink.setAttribute('href', 'data:text/csv;base64,' + window.btoa(data));
    exportLink.appendChild(document.createTextNode('test.csv'));
    document.getElementById('results').appendChild(exportLink);
}

Markup:

<input type="number" id="1_1" value="2">,
<input type="number" id="1_2" value="1">,
<input type="number" id="1_3" value="4">,
<input type="number" id="1_4" value="3">
<br>
<input type="number" id="2_1" value="1">,
<input type="number" id="2_2" value="2">,
<input type="number" id="2_3" value="3">,
<input type="number" id="2_4" value="4">
<br>
<button onclick="exportData()">Export as CSV</button>
<div id="results"></div>

Demo:

Click the button you get a link, click the link and you get a file. Change the values, click the link again and you get a different file. Firefox made me select Excel every time to open it but I don't know whether that's my configuration or a general issue.

Live Demo

Demo

Reference:

Is it possible to use any HTML5 fanciness to export local storage to Excel?

Sign up to request clarification or add additional context in comments.

Comments

1

I know this is a old question. Test ummahusla' answer it do works, but a small problem with the downloaded file, in my chrome it will download a no name file.

And after some testing here is the working code to download as csv file.

    data= 'data:application/csv;charset=utf-8,' + encodeURIComponent(data);
    var exportLink = document.createElement('a');
    exportLink.setAttribute('href', data);
    exportLink.setAttribute('download','test.csv');
    exportLink.setAttribute('target','_blank');
    exportLink.appendChild(document.createTextNode('test.csv'));

    document.getElementById('results').appendChild(exportLink);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.