JavaScript 讀取CSV文件並轉爲js對象

html部分html

<!-- 建立隱藏file input -->
<button type="button" name="seach" onclick="FuncCSVInport()">CSV Import</button> <input type="file" id="csvFileInput" onchange="readCSVFile(this)" /> #csvFileInput{ position: absolute; right: 0px; opacity: 0; }

js部分this

<script>
    function csvToObject(csvString){ var csvarry = csvString.split("\r\n"); var datas = []; var headers = csvarry[0].split(","); for(var i = 1;i<csvarry.length;i++){ var data = {}; var temp = csvarry[i].split(","); for(var j = 0;j<temp.length;j++){ data[headers[j]] = temp[j]; } datas.push(data); } return datas; } function FuncCSVInport() { $("#csvFileInput").val(""); $("#csvFileInput").click(); } function readCSVFile(obj) { var reader = new FileReader(); reader.readAsText(obj.files[0]); reader.onload = function () { var data = csvToObject(this.result); console.log(data);//data爲csv轉換後的對象 } } </script>
相關文章
相關標籤/搜索