需要依赖 xlsx.js 插件,插件可自行到官网下载最新依赖
效果图:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JS Excel导入表格数据</title> <style> table { border: 1px solid black; border-collapse: collapse; } th, td { padding: 5px; } </style> </head> <body> <input type="file" onchange="readExcel(this)" /> <div id="d1"></div> <script src="xlsx.full.min.js"></script> <script> function readExcel(file_obj) { let reader = new FileReader(); let file = file_obj.files[0]; reader.readAsBinaryString(file); reader.onload = function (e) { let data = e.target.result; let wb = XLSX.read(data, { type: 'binary' }); sheetName = wb.SheetNames[0] // 获取文档中第一个sheet页签的名字 sheets = wb.Sheets[sheetName] // 获sheet名页签下的数据 // console.log(sheets); const htmlList = XLSX.utils.sheet_to_json(sheets) // sheet页签的内容转化为json数据 // console.log(htmlList); let html = '' let state = false // 判断是否表格 for (const item of htmlList) { // 开始渲染表格,设置属性 if (item.__EMPTY === ' <table>') { state = true item.__EMPTY = ' <table border="1" id="mytable">' } // 结束渲染表格 if (item.__EMPTY === ' </table>') { state = false html += item.__EMPTY } if (state === false) continue // 渲染格子 for (const key in item) { const element = item[key]; html += element } } document.getElementById('d1').innerHTML = html }; }</script> </body> </html>
标签:sheet,Excel,JS,item,导入,let,file,const,EMPTY From: https://www.cnblogs.com/konghaowei/p/16911389.html