导入组件
npm install xlsx
yarn add xlsx
主要代码流程
<Upload {...uploadprops}>
<Button type="primary">
데이터 가져오기
</Button>
</Upload>
const tansfomer =(arraylist) => {
let attributeList = arraylist[0];
let tempdata = [];
let slicedList = arraylist.slice(1);
slicedList.map(item => {
let tempobject = {};
item.forEach((item, index) => {
tempobject[attributeList[index]] = item;
});
tempdata.push(tempobject);
});
return tempdata;
};
const formatterTime = (val)=>{
return val instanceof Date ? moment(val).format("YYYY-MM-DD"):val;
}
const rowSelection = {
onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
console.log(
`selectedRowKeys: ${selectedRowKeys}`,
'selectedRows: ',
selectedRows,
);
},
getCheckboxProps: (record: DataType) => ({
disabled: record.name === 'Disabled User', // Column configuration not to be checked
name: record.name,
}),
};
const uploadprops = {
name: 'file',
accept:'.xlsx,.xls',
headers: {
authorization: 'authorization-text',
},
showUploadList: false,
beforeUpload: (file, fileList) => {
const rABS = true;
const f = fileList[0];
const reader = new FileReader();
reader.onload = e => {
let dataResult = e.target.result;
// if (!rABS) dataResult = new Uint8Array(dataResult);
const workbook = read(dataResult, {
type: rABS ? 'binary' : 'array',
cellDates: true
});
const firstWorksheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonArr =utils.sheet_to_json(firstWorksheet, { header: 1,rawNumbers:false });
if (jsonArr.length>0){
let listData =[]
jsonArr[0].forEach(item=>{
let obj= {
title: item,
dataIndex: item,
key: item,
align: 'center',
render:formatterTime
}
listData.push(obj)
})
setDataSource([]);
setColumns([])
setColumns(listData);
let list =[]
jsonArr.forEach(item=>{
let newData =[];
for (let i=0;i<jsonArr[0].length;i++){
let data = item[i];
if (data===undefined){
data=''
}
newData.push(data)
}
list.push(newData)
});
let changList =tansfomer(list);
setDataSource(changList)
message.success('가져오기 성공하였습니다!');
}
};
if (rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
return false;
},
};