JS/VUE按钮点击excel上传文件解析文件内容
代码如示
import * as XLSX from 'xlsx'; // 导入xlsx库
importFile() {
const fileType = ['xlsx', 'xls']
const inputFile = document.createElement('input')
inputFile.type = 'file'
inputFile.style.display = 'none'
inputFile.accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
document.body.appendChild(inputFile)
inputFile.click()
inputFile.addEventListener('change', () => {
const file = inputFile.files[0]
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
if (!fileType.includes(testmsg)) {
this.$message.warning('上传的文件格式只能是,xlsx,xls')
document.body.removeChild(inputFile)
return false
}
//读取xlsx文件数据转换成js数据
const reader = new FileReader();
reader.onload = (e) => {
const data = e.target.result;
const workbook = XLSX.read(data, { type: 'binary' });
// 假设第一个工作表是我们需要的数据
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
// 将工作表转换为JSON
const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
// 处理JSON数据
console.log('json',json);
// 这里可以对json进行进一步处理,例如展示在界面上
document.body.removeChild(inputFile); // 清除临时创建的input元素
};
reader.onerror = (err) => {
console.error('Error reading file:', err);
document.body.removeChild(inputFile);
};
reader.readAsBinaryString(file);
})
},
蜀ICP备16028301号-5