1、引入js文件,如下
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://cdn.bootcss.com/xlsx/0.15.1/xlsx.core.min.js"></script>
2、判断文件是否是excel文件
var url=$('#excel-file').val();
if(!url){return;}
var suffix=url.substring(url.lastIndexOf(".")+1,url.length);
if(!(suffix=="xls"||suffix=="xlsx")){return alert("文件类型不正确");
}
3、读取excel的sheet数据
var files = e.target.files;
var fileReader = new FileReader();/**以二进制方式打开文件*/
fileReader.readAsArrayBuffer(files[0]);
fileReader.onload = function (ev) {try {var data = ev.target.result;var workbook = XLSX.read(data, { type: 'array' }),persons = [];} catch (e) {console.error(e);return alert('文件类型不正确!');}//遍历每张表读取for (var sheet in workbook.Sheets) {if (workbook.Sheets.hasOwnProperty(sheet)) {persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet], { raw: true, header: 1 }));for ( var i = 0; i <persons.length; i++){var person=persons[i];var tr='<tr id="tr-'+i+'">';for (var j = 0; j <person.length; j++){tr+='<td>'+$.trim(person[j]?person[j]:"")+'</td>';}for (var k = 0; k < (6-person.length); k++) {tr+='<td></td>';}if(person.length>1){tr+='<td style="padding:6px;"><a href="javascript:$(\'#tr-'+i+'\').remove();" class="btn btn-danger btn-xs">删除</a></td></tr>';$("#context").append(tr);}}break;// 如果只取第一张表,就把beak注释取消}}
};