JavaScript Implements Exporting CSV Files

Keywords: Javascript JSON IE Attribute

The data structure obtained through the interface is as shown above, and now the data is exported through JavaScript:

    <script type="text/javascript" src="json2csv.js"></script>
    <script type="text/javascript">
        var title = Object.keys(jsonData.list[0]);
        var csv = json2csv({data: jsonData.list, fields: title});

        // Method 1:
    	var exportFun = function(content, filename) {
    		var eLink = document.createElement('a');
    		eLink.download = filename;
    		eLink.style.display = 'none';
    		// Converting character content to blob address
    		var blob = new Blob([content]);
    		eLink.href = URL.createObjectURL(blob);
    		// Trigger Click
    		document.body.appendChild(eLink);
    		eLink.click();
    		// remove
    		document.body.removeChild(eLink);
    	};
    	if('download' in document.createElement('a')) {
    		exportFun(csv, 'test.csv');
    	}
    	else {
    		alert('Browser does not support');
    	}

    	/*// Method 2:
        const BOM = '\uFEFF';
    	function exportCsv(data, filename) {
    		if(navigator.msSaveOrOpenBlob) {  // for IE
    			let blob = new Blob([BOM+csv], {type:'text/csv;charset=utf-8;'});
    			navigator.msSaveOrOpenBlob(blob, filename);
    		}
    		else {
    			let uri = encodeURI(`data:text/csv;charset=utf-8,${BOM}${csv}`);
    			let eLink = document.createElement('a');
    			eLink.href = uri;
    			eLink.download = filename;
    			document.body.appendChild(eLink);
    			eLink.click();
    			document.body.removeChild(eLink);
    		}
    	}
    	exportCsv(csv, 'test2.csv');
        */
    </script>

json2csv.js is an encapsulated tool for converting json data into CSV format, which can be_stamped_in_obtained:

        https://download.csdn.net/download/u014395524/11817408

After exporting the csv file, the colleagues of the requirement expressed their dissatisfaction. They said: 1. The header information of the exported file is area_id, author_name, category... This kind of information; 2. The field information of the exported file is too much, and the order is unreasonable. They hope to specify which fields to export and the related order. So there's the next version:

    <script type="text/javascript">
        // Attribute mapping
        var map = {news_id:"Journalism id",title:"News headlines",provider_name:"provider",author_name:"Content source",sub_type:"Subtype",times:"Reading volume",import_user:"Founder",import_time:"Creation time",release_user:"Publisher",release_time:"Release time",synopsis:"detailed information",is_public:"Is it public?"};
        // The field information to be exported
        var title = ['news_id','title','provider_name','author_name','sub_type','times','import_user','import_time','release_user','release_time','synopsis','is_public'];
        // Export the table header information that the file actually displays
        var titleName = [];
        title.forEach(function(item, index) {
            titleName.push(map[item]);
        });

        // Data to be exported
        var tmpData = [];
        jsonData.list.forEach(function(item, index) {
            let props = Object.keys(item);
            let obj = {};
            props.forEach(function(prop){
                if(~title.indexOf(prop)) {
                    if(prop=='is_public') {
                        obj[map[prop]] = item[prop]==1?'yes':'no';
                    }
                    else {
                        obj[map[prop]] = item[prop];
                    }
                }
            });
            tmpData.push(obj);
        });
        var csv = json2csv({data: tmpData, fields: titleName});
        exportFun(csv, 'test.csv');
        // exportCsv(csv, 'test2.csv');
    </script>

Export format:

The above is only for data export, some scenarios need to export data from table tables, so we need to organize the data in table into csv format by ourselves:

    <script>
        $(document).on("click", "#productqueryOutXls", function () {
            var $trs = $("#alternatecolor").find("tr");
            var str = "";
            for (var i = 0; i < $trs.length; i++) {
                var $tds = $trs.eq(i).find("td,th");
                for (var j = 0; j < $tds.length; j++) {
                    str += $tds.eq(j).text() + ",";
                }
                str += "\n";
            }
 
            var aaaa = "data:text/csv;charset=utf-8,\ufeff" + str;
            var link = document.createElement("a");
            link.setAttribute("href", aaaa);
            var date=new Date().getTime();
            var filename = new Date(date).toLocaleDateString();
            link.setAttribute("download", filename + ".csv");
            link.click();
        });
	</script>

Finally, a more detailed article is attached.< A thorough understanding of using JavaScript to export Json data to CSV files>:

        https://segmentfault.com/a/1190000011389463

Posted by sbrinley on Mon, 07 Oct 2019 00:41:33 -0700