JavaScript 解析 Excel 并上传主要涉及以下基础概念和技术:
.xls
和 .xlsx
。.xlsx
是基于 XML 的 Open XML 格式,而 .xls
是较旧的二进制格式。SheetJS
(也称为 xlsx
)。xlsx
模块)进行解析。以下是一个简单的示例,展示如何使用 SheetJS
在前端解析 Excel 文件并上传数据:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Excel Upload</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.full.min.js"></script>
</head>
<body>
<input type="file" id="excel-file" accept=".xls,.xlsx" />
<button onclick="uploadFile()">Upload</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
function uploadFile() {
const fileInput = document.getElementById('excel-file');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, {type: 'array'});
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const json = XLSX.utils.sheet_to_json(worksheet, {header: 1});
// 处理数据并上传
console.log(json);
document.getElementById('output').innerText = JSON.stringify(json, null, 2);
// 这里可以添加上传数据到服务器的逻辑
// fetch('/upload', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(json)
// }).then(response => response.json())
// .then(data => console.log('Success:', data))
// .catch((error) => console.error('Error:', error));
};
reader.readAsArrayBuffer(file);
}
}
.xlsx
格式,或者使用兼容性更好的库。通过上述方法和示例代码,可以有效地在前端解析 Excel 文件并进行上传操作。如果需要更复杂的处理逻辑或更高的性能,可以考虑将部分任务转移到服务器端执行。
领取专属 10元无门槛券
手把手带您无忧上云