使用XLSX解析excel表格

yarn add [email protected]
npm install [email protected]

可解析excel中行、列合并单元格

	/**
	 * 解析excel数据为组件Table数据
	 * @param {*} file excel文件
	 * @param {*} fields 表格列字段 {[excel表头]: Table组件dataIndex}
	 * @returns []
	 */
	const parseExcel = (file, fields) => {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.onload = (e) => {
				try {
					const data = new Uint8Array(e.target.result);
					const workbook = XLSX.read(data, { type: 'array' });
					const sheet = workbook.Sheets[workbook.SheetNames[0]];
					// console.log(sheet, 'sheet');
					const json = XLSX.utils.sheet_to_json(sheet, {
						header: 1,
						raw: false,
					});
					// console.log(json, 'json');
					const merged = getMergedCells(sheet['!merges']);
					// console.log(merged, 'merged');
					const dataSource = json2List(json, merged, fields);
					// console.log(dataSource, 'dataSource');
					resolve(dataSource);
				} catch (error) {
					reject(error);
				}
			};
			reader.readAsArrayBuffer(file);
		});
	};

	const getMergedCells = (merges) => {
		const result = [];
		// [A-Z] -> 65-90
		if (merges) {
			for (let i = 0; i < merges.length; i++) {
				const merge = merges[i];
				const start = merge.s;
				const end = merge.e;
				const range = {
					rowStart: start.r,
					rowEnd: end.r,
					colStart: start.c,
					colEnd: end.c,
				};
				result.push(range);
			}
		}
		return result;
	};

	const json2List = (json, merges, fields) => {
		const deepJson = JSON.parse(JSON.stringify(json));
		for (let i = 0; i < merges.length; i++) {
			const data = merges[i];
			const value = deepJson[data.rowStart][data.colStart];
			for (let j = data.rowStart + 1; j <= data.rowEnd; j++) {
				deepJson[j][data.colStart] = value;
			}
			for (let j = data.colStart + 1; j <= data.colEnd; j++) {
				deepJson[data.rowStart][j] = value;
			}
		}
		// console.log(deepJson, 'deepJson');
		const [header, ...list] = deepJson;
		const nlist = list.map((item) => {
			const obj = {};
			item.forEach((v, i) => {
				obj[header[i]] = v;
			});

			const objZhKey2EnKey = {};
			Object.entries(fields).forEach((info) => {
				const [key, value] = info;
				objZhKey2EnKey[value] = obj[key];
			});

			return objZhKey2EnKey;
		});

		return nlist;
	};

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