1.此功能用的vue3+antdesignVue3
<a-upload
:data="uploadData"
:action="false"
name="file"
:multiple="false"
ref="upload"
:before-upload="beforeUpload"
>
<a-button type="primary">上传EXCELa-button>
a-upload>
[{classifyName:"酒水饮料",costPrice:2.5,name:"红牛",needSale:1,salePrice: 6,specification: "瓶",stockNum: 10}]
import { ref, reactive} from "vue";
import { Form, Modal, message } from "ant-design-vue";
let uploadData = reactive();
//上传方法
const beforeUpload = (file) => {
console.log("获取数据111", file);
uploadExcel(file);
return false; // 阻止自动上传
};
const uploadExcel = (file) => {
console.log("进来api", file);
const reader = new FileReader();
reader.onload = (e) => {
const data = e.target.result;
//因为表格表头是中文,所有需要中文转为需要传给后端的参数,以下名字必须和表格标题栏保持一致
const tableData = filters.parseTableData(data, [
"名称",
"分类",
"规格",
"库存",
"成本价",
"销售单价(在售必填,停售不填,在售商品未设置时默认0元)",
"是否销售(是/否,不销售的商品仅库存管理)",
]);
//传入表格字段不符合/或者传入表格字段少一列
if (!tableData) {
return;
}
//处理数据
const mapObj = {
"名称": "name",
"分类": "classifyName",
规格: "specification",
"库存": "stockNum",
成本价: "costPrice",
"销售单价(在售必填,停售不填,在售商品未设置时默认0元)": "salePrice",
"是否销售(是/否,不销售的商品仅库存管理)": "needSale",
};
let resultData = filters.dealWithApi(tableData, mapObj);
//判断数组对象是否为空
// 假设需要检测的属性为 "name" 和 "age"
const requiredProps = [
"name",
"classifyName",
"specification",
"stockNum",
"costPrice",
"salePrice",
"needSale",
];
let checkString = "";
//过滤出空数据
resultData = resultData.filter((item, index) => {
return item.classifyName && item.name
})
// console.log('过滤为空的数据', resultData);
resultData.forEach((item) => {
requiredProps.forEach((prop) => {
if (
item[prop] == null ||
item[prop] === "" ||
item[prop] == undefined
) {
checkString = `对象 ${item.id} 的属性 ${prop} 不能为空`;
// console.log(`对象 ${item.id} 的属性 ${prop} 不能为空`);
}
});
});
// console.log("拿到的检查结果", checkString);
//检测数据值是否为空,有值代表数据有空值
if (checkString) {
console.log("请检查是否有数据字段是否为空值!")
return;
}
let updateObj = {
batchInfos: resultData,
operator: userNickname.value, //操作人
};
batchAddApi(updateObj);
};
reader.readAsBinaryString(file);
// console.log("过来了???");
};
//前端解析的数据传给后端
let batchAddApi = (data) => {
batchAdd(data).then((res) => {
if (res.code != 0) {
return;
}
message.success('导入成功');
//导入成功后更新列表
// queryListApi();
});
};