js前端解析excel文件
使用纯Javascript解析excel文件。
使用的是开源的解析excel的js库:sheetjs。github地址:https://github.com/SheetJS/js-xlsx
首先引用JS库
<</span>script src="od.js"></</span>script>
<</span>script src="jszip.js"></</span>script>
<</span>script src="xlsx.js"></</span>script>
放置页面组件
<</span>body>
<</span>div id="drop">Drop an XLSX / XLSM / XLSB / ODS / XLS / XML file here to see sheet data</</span>div>
<</span>p><</span>input type="file" name="xlfile" id="xlf" /> ... or click here to select a file</</span>p> </</span>body>
给dom元素添加监听
function addLis() { var xlf = document.getElementByIdx_x('xlf'); var drop = document.getElementByIdx_x('drop'); drop.addEventListener("dragenter", handleDragover, false); drop.addEventListener("dragover", handleDragover, false); drop.addEventListener("drop", onDropDown, false); if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false); } addLis(); function handleDragover(e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; } function onDropDown(e) { e.stopPropagation(); e.preventDefault(); var files = e.dataTransfer.files; var f = files[0]; readFile(f); } function handleFile(e) { var files = e.target.files; var f = files[0]; readFile(f); }
读取文档并输出到控制台:
function readFile(file) { var name = file.name; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; var wb = XLSX.read(data, { type: "binary" }); console.log(wb); }; reader.readAsBinaryString(file); }
输出示例: