前言
以往datagrid導出數據全部在后台搞定,現在就想換中思路去解決,正常情況下使用easyui datagrid ajax獲取數據源時都是json格式,那么此時需要導出數據時只要把該數據源扔出來直接導出CSV即可。
中文亂碼
導出CSV后,字母和數字正常,中文成了亂碼,一番google發現,有人提出用BOM的方式解決,主要是在導出路徑添加后綴 \uFEFF
導出方法
1 function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { 2 //If JSONData is not an object then JSON.parse will parse the JSON string in an Object 3 var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; 4 5 var CSV = ''; 6 //Set Report title in first row or line 7 8 CSV += ReportTitle + '\r\n\n'; 9 10 //This condition will generate the Label/Header 11 if (ShowLabel) { 12 var row = ""; 13 14 //This loop will extract the label from 1st index of on array 15 for (var index in arrData[0]) { 16 17 //Now convert each value to string and comma-seprated 18 row += index + ','; 19 } 20 21 row = row.slice(0, -1); 22 23 //append Label row with line break 24 CSV += row + '\r\n'; 25 } 26 27 //1st loop is to extract each row 28 for (var i = 0; i < arrData.length; i++) { 29 var row = ""; 30 31 //2nd loop will extract each column and convert it in string comma-seprated 32 for (var index in arrData[i]) { 33 row += '"' + arrData[i][index] + '",'; 34 } 35 36 row.slice(0, row.length - 1); 37 38 //add a line break after each row 39 CSV += row + '\r\n'; 40 } 41 42 if (CSV == '') { 43 alert("Invalid data"); 44 return; 45 } 46 47 //Generate a file name 48 var fileName = ""; 49 //this will remove the blank-spaces from the title and replace it with an underscore 50 fileName += ReportTitle.replace(/ /g, "_"); 51 52 //Initialize file format you want csv or xls 53 var uri = 'data:text/csv;charset=utf-8,\uFEFF' + encodeURI(CSV); 54 55 // Now the little tricky part. 56 // you can use either>> window.open(uri); 57 // but this will not work in some browsers 58 // or you will not get the correct file extension 59 60 //this trick will generate a temp <a /> tag 61 var link = document.createElement("a"); 62 link.href = uri; 63 64 //set the visibility hidden so it will not effect on your web-layout 65 link.style = "visibility:hidden"; 66 link.download = fileName + ".csv"; 67 68 //this part will append the anchor tag and remove it after automatic click 69 document.body.appendChild(link); 70 link.click(); 71 document.body.removeChild(link); 72 }