安裝xlsx
npm intall xlsx --save
文件代碼
// 導入文件
import XLSX from 'xlsx';
// react讀取文件內(nèi)容
@connect(state => state)
export default class ImportExcel extends Component {
constructor(props) {
super(props);
this.state = {
uploadList : [],
};
}
_importExcel = (e) => {
const self = this;
const files = e.target.files[0];
const fileReader = new FileReader();
// 如果IE 瀏覽器 不支持FileReader
const File_Status = FileReader.prototype.readAsBinaryString;
File_Status ? fileReader.readAsBinaryString(files) : fileReader.readAsArrayBuffer(files);
fileReader.onload = function(ev) {
fileReader.onload = function(ev) {
try {
let data = ev.target.result,
workbook = XLSX.read(data, {type: File_Status ? "binary" : "array"}),
persons = []; // 存儲獲取到的數(shù)據(jù)
// 表格的表格范圍荣暮,可用于判斷表頭是否數(shù)量是否正確
let fromTo = "";
// 遍歷每張表讀取
for (let sheet in workbook.Sheets) {
if (workbook.Sheets.hasOwnProperty(sheet)) {
fromTo = workbook.Sheets[sheet]['!ref'];
persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
}
}
console.log(persons);
self.setState({uploadList:persons},() => self._saveXLSXData())
} catch (e) {
self.file.value = "";
console.log("文件類型不正確!");
return;
}
};
};
/**
* 保存并上傳的數(shù)據(jù)到數(shù)據(jù)庫
* @private 該方法是把數(shù)據(jù)發(fā)送到服務器, 請求方法自己處理
*/
_saveXLSXData = () => {
const {uploadList} = this.state;
let data = {
data : uploadList,
};
const self = this;
return new Promise( async (ps,pe)=>{
this.file.value = "";
let res = await AxiosFn('/maintain/saveStudents', data , "POST").catch((e) => {});
if (res && (res.code === 0)) {
message.success("數(shù)據(jù)添加成功!");
this.setState({uploadList : []});
self.getPageData();
}
ps();
});
};
render(){
return(
<div style={{marginRight: 15,width:120, border:"1px solid #ccc",borderRadius:5,padding:"6px 12px",position:"relative"}}>
數(shù)據(jù)導入
<input
ref={(file) => this.file = file }
type="file"
onChange={this.importExcel}
style={{position: 'absolute', top: 0, left: 0,width: '100%',zIndex:999,opacity:0}}
/>
</div>
)
}
};