导入文件用到一个 xlsx.core.js 的包。
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="./xlsx.core.min.js"></script>
<title>Document</title>
</head>
<body>
<input type="file" id="file" style="display:none;" />
<button onclick="importFile()">导入</button>
</body>
<script type="text/javascript" src="./index.js"></script>
</html>
隐藏 input 框,加一个 button 按钮可以方便的调节按钮的样式。
javascript
function importFile() {
console.log('导入');
document.getElementById('file').click();
}
document.getElementById('file').addEventListener('change', function (e) {
let files = e.target.files;
if (files.length == 0) return;
let f = files[0];
if (!/\.xlsx$/g.test(f.name)) {
alert('仅支持读取xlsx格式!');
return;
}
e.target.value = "" // 清空上一次上传的数据,防止第二次无法上传
readWorkbookFromLocalFile(f, function (workbook) {
readWorkbook(workbook);
});
});
function readWorkbookFromLocalFile(file, callback) {
let reader = new FileReader();
reader.onload = function (e) {
let data = e.target.result;
let workbook = XLSX.read(data, { type: 'binary' });
if (callback) callback(workbook);
};
reader.readAsBinaryString(file);
}
function readWorkbook(workbook) {
let sheetNames = workbook.SheetNames; // 工作表名称集合
console.log(sheetNames, 'sheetNames');
let worksheet = workbook.Sheets[sheetNames[0]]; // 读取第一张sheet
console.log(worksheet, 'worksheet');
let json = XLSX.utils.sheet_to_json(worksheet);
// let json = XLSX.utils.sheet_to_json(worksheet, { range: 1 }) // range: 1 可以设置是从第几行开始读,不设置从第一行开始读
console.log(json, 'json');
}
文件信息。
页面上取值。