以下是一个完整的 HTML 文件,使用 ExcelJS
处理 Excel 文件上传,并将解析后的数据发送给后端的 ThinkPHP 5 API:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Excel 文件上传和解析</title> <script src="https://cdn.jsdelivr.net/npm/exceljs/dist/exceljs.min.js"></script> </head> <body> <h1>上传 Excel 文件</h1> <input type="file" id="uploadExcel" accept=".xlsx, .xls" /> <p id="status"></p> <script> document.getElementById("uploadExcel").addEventListener("change", async (event) => { const file = event.target.files[0]; if (!file) { document.getElementById("status").textContent = "请选择一个文件"; return; } const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(file); const worksheet = workbook.getWorksheet(1); // 获取第一个工作表 const rows = []; worksheet.eachRow((row, rowNumber) => { const rowData = row.values.slice(1); // 获取每一行的值 (去掉第一列为空的空值) rows.push(rowData); }); // 将解析后的数据传递给后端 uploadToBackend(rows); }); function uploadToBackend(rows) { fetch('/path/to/your/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: rows }) }) .then(response => response.json()) .then(data => { document.getElementById("status").textContent = "上传成功: " + data.msg; console.log("上传成功", data); }) .catch(error => { document.getElementById("status").textContent = "上传失败,请检查控制台日志"; console.error("上传失败", error); }); } </script> </body> </html>
<?php echo file_get_contents("php://input");