js前端解析excel文件
使用纯Javascript解析excel文件。
使用的是开源的解析excel的js库:sheetjs。github地址:https://github.com/SheetJS/js-xlsx
首先引用JS库
<script src="od.js"></script> <script src="jszip.js"></script> <script src="xlsx.js"></script>
放置页面组件
<body> <div id="drop">Drop an XLSX / XLSM / XLSB / ODS / XLS / XML file here to see sheet data</div> <p><input type="file" name="xlfile" id="xlf" /> ... or click here to select a file</p> </body>
页面效果如下:
给dom元素添加监听
function addLis() { var xlf = document.getElementById(\'xlf\'); var drop = document.getElementById(\'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); }
输出示例:
版权声明:本文为Leechg原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。