2022-06-16 js 导入excel并渲染成table显示(转载)
作者:互联网
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="https://cdn.bootcss.com/xlsx/0.12.7/xlsx.core.min.js"></script> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 5px; } </style> </head> <body> <!-- 1.文件选择框 --> <input type="file" id="file01"> <!-- 2.上传文件按钮 --> <button id="btnUpload">上传文件</button> <!--bootstrap进度条--> <div class="progress" style="width: 500px;margin: 15px 10px;"> <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">0%</div> <table id="demo01"></table> </div> <img src="./img/loading.gif" style="display: none;" alt="" id="loading"> <!-- 3.img标签,来选择上传文件后的图片 --> <img src="" alt="" id="img" width="800"> <script> $('#btnUpload').on('click', function () { var files = $('#file01')[0].files[0];//文件对象 // console.log(files); var file_name = files['name'];//文件名称 var index = file_name.lastIndexOf("."); if (index != -1) { file_format = file_name.substr(index + 1).toUpperCase();//文件格式后缀 if (file_format != 'XLS' && file_format != 'XLSX') { alert("只能上传.xls和.xlsx类型的文件!"); } else { //读取文件内容 var reader = new FileReader(); reader.readAsBinaryString(files); reader.onload = function (e) { var data = e.target.result; var wb = XLSX.read(data, { type: 'binary' // 以二进制流方式读取获得整份excel表格对象 }); var sheet_names = wb.SheetNames;//获取excel中所有表名称 // console.log(sheet_name); var sheet1_name = sheet_names[0];//获取excel中第一张表名称 var sheet01_obj = XLSX.utils.sheet_to_json(wb.Sheets[sheet1_name]);//获取excel中第一张表数据,数组类型,每一行数据都是一个对象 // console.log(sheet01_obj); // console.log(sheet01_obj.length); var table1 = ""; var table2 = ""; var table3 = ""; var keyArr = []; table1 += "<tr>"; for (var key01 in sheet01_obj[0]) { keyArr.push(key01); table1 += '<th nowrap>' + key01 + '</th>';//表头 // var table="<tr><th>Artist</th><th>Title</th></tr>"; // console.log(table1); }; table2 += "</tr>"; // console.log(table1); for (var i = 0; i < sheet01_obj.length; i++) { table2 += "<tr>"; for (var j in sheet01_obj[i]) { // console.log('value:'+j); table2 += '<td nowrap>' + sheet01_obj[i][j] + '</td>';//表数据 }; table2 += "</tr>"; } console.log(table1 + table2); document.getElementById("demo01").innerHTML = table1 + table2; } } } }); </script> </body> </html>
注:本文转载于https://www.cnblogs.com/doradora/p/15305511.html
主要用到2个工具,一是jQuery,二是SheetJS,二者皆是外链,拿过去就可以用,我这里只测了导入的功能,导出我不晓得。
标签:table2,table1,console,log,16,excel,var,06,name 来源: https://www.cnblogs.com/iuniko/p/16381690.html