使用xlsxjs导入导出excel

解析excel
export const parseFile = (file) => {
	return new Promise((resolve,reject) => {
        let reader = new FileReader();
        reader.readAsBinaryString(file);//以二进制的方式读取
        reader.onload = ev =>{
			let data = ev.target.result;
			let workbook = XLSX.read(data,{ type: "binary"});//解析二进制格式数据
			//解析第一张sheet
			let worksheet = workbook.Sheets[workbook.SheetNames[0]];
			let result = XLSX.utils.sheet_to_json(worksheet);
			resolve({
				code:200,
				data:result,
				message:'解析成功'
			})
        }

	}).catch(error=>{
		reject({
			code:400,
			message:'解析失败'
		})
	})
}
导出excel
export const exportFile = ({ header = [], body = [], fileName = '数据' }) => {
	return new Promise((resolve, reject) => {
		if (header.length === 0 || body.length === 0) {
			throw '导出的数据不能为空';
		}
		let data = body.map((item) => {
			let newitem = {};
			Object.keys(header).forEach((key) => {
				newitem[header[key]] = item[key];
			});
			return newitem;
		});
		let sheet = XLSX.utils.json_to_sheet(data);
		let book = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(book, sheet, 'sheet1');
		XLSX.writeFile(book, `${fileName}.xls`);
		resolve(true);
	}).catch((error) => {
		reject(false);
	});
};

你可能感兴趣的:(excel,前端,javascript)