Using javascript to download file as a.csv file

前端 未结 6 1447
难免孤独
难免孤独 2020-12-01 06:54

Hi I am trying to export a file as .csv file, so that when the user clicks on the download button, the browser would automatically download the file as .csv. I also want to

6条回答
  •  星月不相逢
    2020-12-01 07:20

    I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.

    I use $.getJSON to pull json data from an external page, but if you have a basic array, you can just use that.

    This uses Christian Landgren's code to create the csv data.

    $(document).ready(function() {
        var JSONData = $.getJSON("GetJsonData.php", function(data) {
            var items = data;
            const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
            const header = Object.keys(items[0]);
            let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
            csv.unshift(header.join(','));
            csv = csv.join('\r\n');
    
            //Download the file as CSV
            var downloadLink = document.createElement("a");
            var blob = new Blob(["\ufeff", csv]);
            var url = URL.createObjectURL(blob);
            downloadLink.href = url;
            downloadLink.download = "DataDump.csv";  //Name the file here
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        });
    });
    

    Edit: It's worth noting that JSON.stringify will escape quotes in quotes by adding \". If you view the CSV in excel, it doesn't like that as an escape character.

    You can add .replace(/\\"/g, '""') to the end of JSON.stringify(row[fieldName], replacer) to display this properly in excel (this will replace \" with "" which is what excel prefers).

    Full Line: JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""')

提交回复
热议问题