Excel Import
html Code
<button style={{ color: '#1890ff', fontSize: '14px', cursor: 'pointer' }} onClick={() => { upFile(); }} >
Import
</button>
<input id="upFile" type="file" style={{ display: 'none' }} accept=".xlsx, .xls" onChange={upChange} />
js Code
import XLSX from 'xlsx';
const upFile = () => {
const upSdaFile: any = document.getElementById('upFile');
upSdaFile.click();
};
const upChange = (e) => {
const file = e.target.files[0]; // Get the first file
const reader = new FileReader();
reader.readAsBinaryString(file); // Read this file
reader.onload = function (event) {
try {
const { result }: any = event.target;
const xlsxData = XLSX.read(result, { type: 'binary' }); // Read xlsx
let col: any = null;
// @ts-ignore
for (const n in xlsxData.Sheets) { // eslint-disable-line
// Here are several forms So write a loop
col = XLSX.utils.sheet_to_json(xlsxData.Sheets[n], { header: 1, defval: '', blankbook: true }); // Parse to array
}
console.log('col', col);
} catch (err) {
console.log('err', err);
}
};
};
Be careful not to quote 0.18. Several xlsx, It conflicts with other files, and the error message cannot be found , To install "xlsx": "0.17.0"
Excel export
html Code
<Button onClick={() => ecportExcel()} > export </Button>
js Code
const jsonData = [ { name: ' Zhang San ', age: 12, gender: ' male ' }, { name: ' Li Si ', age: 14, gender: ' male ' }, { name: ' Wang Wu ', age: 15, gender: ' Woman ' }, ] // Front end implementation export const ecportExcel = (jsonData: any) => { // Column headings , commas , Each comma is separated by a cell let str = ` Serial number , name , Age , Gender \n`; const tableData: any = [] jsonData.forEach((el: any, index: number) => { tableData.push({ index: index + 1, name: el?.name || '', age: el?.age || '', gender: el?.gender || '', }) }); // increase \t To prevent tables from displaying scientific notation or other formats for (let i = 0; i < tableData.length; i++) { // eslint-disable-line for (const key in tableData[i]) { // eslint-disable-line str += `${`${tableData[i][key]}\t`},`; } str += '\n'; } // encodeURIComponent Solve the Chinese garbled code const uri = `data:text/xlsx;charset=utf-8,\ufeff${encodeURIComponent(str)}`; // By creating a a Tag implementation const link = document.createElement("a"); link.href = uri; // Name the downloaded file link.download = " Summary of enterprise commitments .xlsx"; link.click(); }
You are welcome to pay great attention to !!!