<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>xls的导入</title> </head> <body> <label for="excel-file" class="btn btn-success">导入Excel文件</label> <input type="file" name="excel-file" id="excel-file"/> <br> <table id="context"> </table> </body> </html> <script src="./jquery.js"></script> <script src="./xlsx.core.min.js"></script> <script> $('#excel-file').change(function(e) { console.log(e); try { new Uint8Array([1,2]).slice(0,2); } catch (e) { console.log("[Uint8Array"+e.description+"]这里使用【Array.slice】。"); //IE或有些浏览器不支持Uint8Array.slice()方法。改成使用Array.slice()方法 Uint8Array.prototype.slice = Array.prototype.slice; } var url=$('#excel-file').val(); if(!url){return;} var suffix=url.substring(url.lastIndexOf(".")+1,url.length); if(!(suffix=="xls"||suffix=="xlsx")){ return alert("文件类型不正确"); } var files = e.target.files; var fileReader = new FileReader(); fileReader.readAsArrayBuffer(files[0]);// 以二进制方式打开文件 fileReader.onload = function(ev) { $('#excel-file').val(''); $("#context").html(""); 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})); console.log(persons) 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注释取消 } } }; }); </script>
https://github.com/SheetJS/js-xlsx 这个地址下的 dist 下载xlsx.core.min.js文件 教程连接“http://blog.haoji.me/js-excel.html”