1、html
<div> <el-button type="primary" @click="upload">点击上传</el-button> <input type="file" ref="excelFile" style="display: none" @change="onFileChange" accept=".xlsx, .xls"> </div>
2、
import { read } from 'xlsx';//需要先下载xlsx插件
methods:{
upload() { this.$refs.excelFile.click(); },
onFileChange(event){
const file = event.target.files[0];
const reader = new FileReader();
let flagList = []//装判断一列数据的集合
reader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = read(data, { type: 'array' }); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; //获取第J列一共有多少行 const column = 'J'; // 指定要获取行数的列,这里假设为 J 列 const range = worksheet['!ref'].split(':'); const startRow = parseInt(range[0].match(/\d+/)[0]); const endRow = parseInt(range[1].match(/\d+/)[0]); let rowCount = 0; for (let row = startRow; row <= endRow; row++) { const cellAddress = column + row; const cellValue = worksheet[cellAddress]?.v; if (cellValue !== undefined && cellValue !== null && cellValue.trim() !== '') { rowCount++; } } console.log(`Total rows in column ${column}: ${rowCount}`) for (let row = 2; row <= rowCount; row++) { // 从第2行(假设第一行是标题行)开始验证 const cellValue = worksheet[`${column}${row}`]?.v; // 获取指定列的单元格值 flagList.push(cellValue) // 进行内容验证(可以看到哪些行的数据不合规) // if (cellValue === '自制') { // // 处理符合条件的单元格值 // console.log(`Valid value at ${column}${row}: ${cellValue}`); // } else { // // 错误处理 // console.log(`Invalid value at ${column}${row}: ${cellValue}`); // } } console.log(flagList,14555) let flag = flagList.some(item=>item === '外购') if(!flag){ 如果全都是符合条件的就继续调用上传接口 }else{ this.$message.warning('表格仅允许上传自制的产品') } }; reader.readAsArrayBuffer(file); }