- Published on
Ant Design Vue implements form upload Excel file check row count
- Reading time
- 1 分钟
- Page view
- -
- Author

- Name
- Yicong
- Github
Recently, I encountered such a requirement during development: check the number of rows of the uploaded Excel file, and prompt the user that the data exceeds the limit if the number of rows exceeds 1000. Originally, the check was done by the front end after the user selected the file, and then temporarily changed to the back end after the file was uploaded, but the front end code has been developed, and it is a pity to delete it directly, so I recorded it.
Complete code implementation
<template>
<div id="app">
<a-form :form="batchImportForm">
<!-- 文件上传 -->
<a-form-item label="文件上传">
<a-upload
v-decorator="['uploadFile', fileOption]"
accept=".xlsx,.xls"
:file-list="fileList"
:remove="handleRemove"
:before-upload="handleBeforeUpload"
>
<a-button shape="round">文件上传</a-button>
</a-upload>
</a-form-item>
</a-form>
</div>
</template>
<script>
import * as XLSX from "xlsx";
export default {
name: "App",
data() {
return {
// 批量导入表单
batchImportForm: this.$form.createForm(this),
// 文件列表
fileList: [],
};
},
computed: {
// 文件上传表单校验
fileOption() {
return {
rules: [
{
message: "文件条数超限,最多10条",
validator: this.isFileEntryExceed,
},
],
};
},
},
methods: {
handleRemove() {
this.fileList = [];
},
handleBeforeUpload(file) {
this.fileList = [file];
return false;
},
// 判断文件条数是否超限 10 条,表头不计
isFileEntryExceed(rule, value, callback) {
const reader = new FileReader();
reader.onload = (event) => {
const data = new Uint8Array(event.target.result);
const workbook = XLSX.read(data, { type: "array" });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet);
const rowCount = jsonData.length;
if (rowCount > 10) {
callback(new Error(rule.message));
}
callback();
};
reader.readAsArrayBuffer(value.file);
},
},
};
</script>
行数校验
以 Excel 文件的第一个 Sheet 页为例,使用 xlsx 库将文件转换为 JSON 数据,然后获取数据的长度即可。
// 判断文件条数是否超限 10 条,表头不计
function isFileEntryExceed(rule, value, callback) {
const reader = new FileReader();
reader.onload = (event) => {
const data = new Uint8Array(event.target.result);
const workbook = XLSX.read(data, { type: "array" });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet);
const rowCount = jsonData.length;
// 需要注意的是表头不计入行数
if (rowCount > 10) {
callback(new Error(rule.message));
}
callback();
};
reader.readAsArrayBuffer(value.file);
}