vue antd 解析 Excel
先运行 npm install xlsx
解析方法
export function readExcel (file, that, properties) {
return new Promise(function (resolve, reject) {
// 返回Promise对象
const reader = new FileReader()
reader.onload = (e) => {
// 异步执行
console.log(‘reader.onload:’, e)
try {
// 以二进制流方式读取得到整份excel表格对象
const data = e.target.result
const workbook = XLSX.read(data, { type: ‘binary’ })
const exlname = workbook.SheetNames[0]
// 取第一张表
const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname])
// 生成json表格内容
console.log(‘exl:’, exl)
const arr = []
exl.map(v => {
const obj = {}
properties.map(property => {
obj[property.key] = v[property.value]
})
arr.push(obj)
})
that.exlData = arr
resolve()
} catch (e) {
reject(e.message)
}
}
reader.readAsBinaryString(file)
})
}
控件选择
导入
引入
import AUpload from ‘ant-design-vue/es/upload/Upload’
import { parseToExcel, readExcel } from ‘@/utils/excelUtil’
AUpload
// 导入数据
exlData: {},
// 导入字段设置
properties: [
{ key: 'goodsBarCode', value: '商品销售码' },
{ key: 'goodsNumber', value: '数量' },
{ key: 'goodsPrice', value: '单价' }]
实际业务
// 导入前条件处理
beforeUpload (file) {
if (!this.supplierInfo.supCode) {
this.confirmLoading = false
return this.KaTeX parse error: Expected 'EOF', got '}' at position 32: …择供货商') }̲ else if (!this…message.info(‘请选择仓库’)
}
const that = this
return new Promise(function (resolve, reject) {
readExcel(file, that, that.properties).then(result => {
console.log('that.exlData: ', that.exlData)
if (that.exlData.length > 0) {
for (let i = 0; i < that.exlData.length; i++) {
const { goodsBarCode, goodsPrice, goodsNumber } = that.exlData[i]
that.uploadGoods(goodsBarCode, goodsPrice, goodsNumber)
}
}
if (result) {
resolve(result)
}
})
})
},
// 根据商品销售码查询商品
uploadGoods (goodsBarCode, goodsPrice, goodsNumber) {
// 根据选择的供应商和输入的商品编码查询对应商品
console.log(‘goodsBarCode’, goodsBarCode)
console.log(‘goodsPrice’, goodsPrice)
console.log(‘goodsNumber’, goodsNumber)
getpurchaseGoodsByCode({
goodsBarCode: goodsBarCode,
supCode: this.supplierInfo.supCode,
whCode: this.warehouseInfo.whCode
})
.then(res => {
console.log(‘getGoodsByCode res’, res)
const goods = res.data
if (!goods) {
// 这个动作是为了再下面清数据
return this.KaTeX parse error: Expected 'EOF', got '}' at position 63: …') }̲ if…message.info(‘商品销售码为’ + goodsBarCode + ‘的商品已经存在’)
}
}).finally(() => {
this.confirmLoading = false
})
},