XLSX库失效:前端读取Excel并渲染HTML表格失败求助
问题解决方案
核心问题分析
- script标签使用错误:带有
src属性的script标签不能同时包含内部代码,浏览器会忽略标签内的代码,仅加载外部脚本,这就是添加console.log无输出的根本原因。 - 环境API误用:
XLSX.readFile是Node.js专属API,浏览器环境无法直接通过文件路径读取本地文件;同时浏览器中无需使用require('xlsx'),引入外部XLSX脚本后,XLSX会成为全局可用对象。
修复步骤
- 拆分script标签:一个专门引入XLSX库,另一个单独编写业务逻辑代码。
- 替换文件读取方式:浏览器中读取Excel文件,可通过
fetch加载服务器托管的文件,或通过文件选择控件让用户上传本地文件(两种方案均提供)。 - 移除无用的
require语句,直接使用全局XLSX对象。
服务器文件加载方案(修正后代码)
<!DOCTYPE html> <html> <head> <title>Search Results</title> <style> table { border-collapse: collapse; width: 100%; margin: 0 auto; font-size: 1em; min-width: 400px; } th { background-color: #008CBA; color: white; font-weight: bold; padding: 10px; text-align: left; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; } td { padding: 10px; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; } tr:nth-child(even) { background-color: #f2f2f2; } </style> </head> <body> <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </thead> <tbody id="results"> </tbody> </table> <!-- 单独引入XLSX库 --> <script src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js"></script> <!-- 业务逻辑代码 --> <script> // 假设MM.xlsx放在服务器根目录,用fetch加载文件 fetch('MM.xlsx') .then(response => response.arrayBuffer()) .then(data => { const workbook = XLSX.read(data, { type: 'array' }); const worksheet = workbook.Sheets['Sheet1']; // 将工作表转为数组格式,更易遍历 const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); const searchTerm = 'VIP1'; const resultsTable = document.getElementById('results'); rows.forEach(row => { // 检查当前行是否包含搜索值 if (row.includes(searchTerm)) { const tr = document.createElement('tr'); tr.innerHTML = ` <td>${searchTerm}</td> <td>Data 2</td> <td>Data 3</td> `; resultsTable.appendChild(tr); } }); }) .catch(err => console.error('加载Excel文件失败:', err)); </script> </body> </html>
本地文件上传方案(可选)
如果需要让用户选择本地Excel文件,可添加文件选择控件:
<!-- 在body中添加文件选择框 --> <input type="file" id="excelFile" accept=".xlsx, .xls"> <!-- 修改业务脚本 --> <script> document.getElementById('excelFile').addEventListener('change', function(e) { const file = e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = function(event) { const data = new Uint8Array(event.target.result); const workbook = XLSX.read(data, { type: 'array' }); const worksheet = workbook.Sheets['Sheet1']; const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); const searchTerm = 'VIP1'; const resultsTable = document.getElementById('results'); resultsTable.innerHTML = ''; // 清空之前的查询结果 rows.forEach(row => { if (row.includes(searchTerm)) { const tr = document.createElement('tr'); tr.innerHTML = ` <td>${searchTerm}</td> <td>Data 2</td> <td>Data 3</td> `; resultsTable.appendChild(tr); } }); }; reader.readAsArrayBuffer(file); }); </script>
内容的提问来源于stack exchange,提问作者Hussein
相关产品推荐
相关产品推荐

