简体   繁体   中英

How to export a result from Javascript to a csv file?

I am trying to calculate a person's typing speed and then store it in an csv file. I can calculate the speed using a JavaScript program, but I do not know how to export the speeds to a csv file. I tried using Papaunparse, but that did not work. It's a server side csv file, called stats.

The speed variable is called spd. Below is a snippet of the code that calculates the speed and displays it to the user.

    clearTimeout(myTimer);
    dayTwo = new Date();
    endType = dayTwo.getTime();
    totalTime = ((endType - startType) / 1000)
    spd = Math.round((word/totalTime) * 60)
    given = document.theForm.given.value.split(" ")
    typed = document.theForm.typed.value.split(" ")
    correct = 0
    len = 0 
    if(typed.length > given.length){
        len = typed.length
    }
    else{
        len = given.length
    }
    for (var i = 0; i < len; i++) {
        if(typed[i] === given[i]){
            correct += 1
        }
    }
    alert("\nYou got " + correct + "/" + given.length + "correct. \nYou typed a " + given.length + " word sentence in " 
    + totalTime + " seconds, a speed of about " + spd + " words per minute!" );

If someone could tell me how to export this speed to a csv file, it would be wonderful! Thanks for any help! :)

If you're able to use data: URIs you can store your data on an <a> element with a [download] attribute .

<a href="data:text/csv,[your CSV data here]" download="filename.csv">Download</a>

If you're not able to use data: URIs or the [download] attribute, you'll need to host the data somewhere to be downloaded. This can be done in numerous ways. You could submit the data to a server and prompt the user with a link to download it, or you could render the CSV data on the page in a way the user could copy-paste, such as in a table, or maybe just as a <textarea> of data:

<textarea readonly>[your CSV data here]</textarea>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM