import React, { Component } from 'react'
|
import PropTypes from 'prop-types'
|
import { notification } from 'antd'
|
import * as XLSX from 'xlsx'
|
import Utils from '@/utils/utils.js'
|
import './index.scss'
|
|
class ExcelIn extends Component {
|
static propTpyes = {
|
MenuID: PropTypes.string, // 菜单ID
|
returndata: PropTypes.func // 菜单ID
|
}
|
|
state = {
|
excelbtn: null,
|
primaryId: '', // 行Id
|
excelId: Utils.getuuid()
|
}
|
|
exceltrigger = (item, primaryId) => {
|
const { excelId } = this.state
|
this.setState({
|
excelbtn: item,
|
primaryId: primaryId
|
})
|
|
let _excelInput = document.getElementById(excelId + this.props.MenuID)
|
|
if (_excelInput) {
|
_excelInput.click()
|
}
|
}
|
onImportExcel = file => {
|
const { excelbtn, primaryId } = this.state
|
|
let columns = excelbtn.verify.columns.map(option => option.Column)
|
let range = excelbtn.verify.range || 0
|
|
// excel数据处理
|
const { files } = file.target
|
const fileReader = new FileReader()
|
|
fileReader.onload = event => {
|
try {
|
const { result } = event.target
|
// 以二进制流方式读取得到整份excel表格对象
|
const workbook = XLSX.read(result, { type: 'binary' })
|
|
let errors = null
|
|
if (!workbook.Sheets.hasOwnProperty(excelbtn.verify.sheet)) {
|
errors = 'notexit'
|
} else if (range === 1) {
|
let header = XLSX.utils.sheet_to_json(workbook.Sheets[excelbtn.verify.sheet], {header: columns})[0]
|
|
if (!header) {
|
errors = 'empty'
|
} else {
|
let iserror = false
|
excelbtn.verify.columns.forEach(op => {
|
if (header[op.Column] !== op.Text) {
|
iserror = true
|
}
|
})
|
|
if (iserror) {
|
errors = 'headerError'
|
}
|
}
|
}
|
|
let data = []
|
|
if (!errors) {
|
data = XLSX.utils.sheet_to_json(workbook.Sheets[excelbtn.verify.sheet], {header: columns, range: (range)})
|
}
|
|
// 最终获取到并且格式化后的 json 数据
|
this.props.returndata(data, excelbtn, errors, primaryId)
|
this.setState({
|
excelId: '',
|
primaryId: ''
|
}, () => {
|
this.setState({
|
excelId: Utils.getuuid()
|
})
|
})
|
} catch (e) {
|
this.setState({
|
excelId: ''
|
}, () => {
|
this.setState({
|
excelId: Utils.getuuid()
|
})
|
})
|
notification.warning({
|
top: 92,
|
message: '文件解析错误,请检查文件格式!',
|
duration: 10
|
})
|
}
|
}
|
|
// 以二进制方式打开文件
|
fileReader.readAsBinaryString(files[0])
|
}
|
|
render() {
|
return (
|
<span>
|
{this.state.excelId ? <input className="excel-in-input" id={this.state.excelId + this.props.MenuID} type='file' accept='.xlsx, .xls' onChange={this.onImportExcel} /> : null}
|
</span>
|
)
|
}
|
}
|
|
export default ExcelIn
|