1. 程式人生 > >js讀取xlsx檔案成陣列

js讀取xlsx檔案成陣列

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-2.2.1.min.js" type="text/javascript"></script>
    <script src="xlsx.core.min.js"></script>
</head>
<body>
<input type="file" id="xlsxfile" onchange="ConvertToArray2()"
/>
<script> var sheet2arr = function(sheet){ var result = []; var row; var rowNum; var colNum; var range = XLSX.utils.decode_range(sheet['!ref']); for(rowNum = range.s.r; rowNum <= range.e.r; rowNum++){ row = []; for
(colNum=range.s.c; colNum<=range.e.c; colNum++){ var nextCell = sheet[ XLSX.utils.encode_cell({r: rowNum, c: colNum}) ]; if( typeof nextCell === 'undefined' ){ row.push(void 0); } else row.push(nextCell.w); } result.push(row); } return
result; }; //方法一、xlsx轉成陣列 function ConvertToArray1() { var reader = new FileReader(); reader.readAsBinaryString(document.getElementById("xlsxfile").files[0]); reader.onloadend = function (evt) { if(evt.target.readyState == FileReader.DONE){ var data = reader.result; var workbook = XLSX.read(data, { type: 'binary' }); } var sheet_name_list = workbook.SheetNames; var result = sheet2arr(workbook.Sheets[sheet_name_list[0]]); console.log(result); } } //方法二、xlsx轉成陣列 function ConvertToArray2() { var reader = new FileReader(); reader.readAsBinaryString(document.getElementById("xlsxfile").files[0]); reader.onloadend = function (evt) { if(evt.target.readyState == FileReader.DONE){ var data = reader.result; var workbook = XLSX.read(data, { type: 'binary' }); } var sheet_name_list = workbook.SheetNames; var result = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]], {header:1}); console.log(result); } }
</script> </body> </html>

注意:

需要引用
    jquery-2.2.1.min.js
    xlsx.core.min.js