1.<template>部分
<a-upload
name="file"
:customRequest="importExcelData"
accept=".xls,.xlsx"
class="uploadBtn"
:showUploadList="false"
>
<a-button
type="primary"
style="margin-right: 8px"
:loading="uploading"
>导入excel</a-button
>
</a-upload>
2.导入xlsx
import * as xlsx from "xlsx";
3.<script>部分
//导入excel
const uploading = ref(false);
// 文件上传自定义
const importExcelData = async (op) => {
uploading.value = true;
// 获取上传的excel 并解析数据
let file = op.file;
let dataBinary = await readFile(file);
let workBook = xlsx.read(dataBinary, { type: "binary", cellDates: true });
let workSheet = workBook.Sheets[workBook.SheetNames[0]];
const excelData = xlsx.utils.sheet_to_json(workSheet);
let result = [];
for (let i = 0; i < excelData.length; i++) {
//循环excel数据,将字段名置为英文字符,值为当前项相应表头字段的值,拼成接口需要的数据格式
// 定义要导出的
let sheetData = {
branch: excelData[i]["分公司"], //第i项,对应表头为楼宇名称的列值
grid: excelData[i]["网格"],
buildingId: excelData[i]["楼宇id"],
buildingName: excelData[i]["楼宇名称"],
};
result.push(sheetData);
}
return new Promise((resolve, reject) => {
GzBuildingsApi.importExcelData(result)
.then((response) => {
const data = response.data;
if (data.code === 200) {
message.success("导入成功");
uploading.value = false;
query();
} else {
message.error(data.message);
}
})
.catch((error) => {});
});
};
const readFile = (file) => {
return new Promise((resolve) => {
let reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = (ev) => {
resolve(ev.target?.result);
};
});
};