React前端解析excel文件,获取excel文件中的数据

核心

xlsx

import React, { useEffect } from 'react';
import { Upload, Input } from 'antd';
import XLSX from 'xlsx';

/**
 * 将 file 转为一个 CSF 的 JSON
 * @param {File} file
 * @returns sheet
 */
const analyseExcelToJson = (file) => {
	return new Promise((resolve, reject) => {
		if (file instanceof File) {
			const reader = new FileReader();
			reader.onloadend = (progressEvent) => {
				const arrayBuffer = reader.result;
				const options = { type: 'array' };
				const workbook = XLSX.read(arrayBuffer, options);
				const sheetName = workbook.SheetNames;
				const sheet = workbook.Sheets[sheetName];
				resolve(sheet);
			};
			reader.readAsArrayBuffer(file);
		} else {
			reject(new Error('入参不是 File 类型'));
		}
	});
};

function getFileFromUrl(url, fileName) {
  return new Promise((resolve, reject) => {
    var blob = null;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.setRequestHeader('Accept', 'image/png');
    xhr.responseType = "blob";
    // 加载时处理
    xhr.onload = () => {
      // 获取返回结果
      blob = xhr.response;
      let file= new File([blob], fileName, { type: 'image/png' });
      // 返回结果
      resolve(file);
    };
    xhr.onerror = (e) => {
      reject(e)
    };
    // 发送
    xhr.send();
  });
}


export default function GetExcelInfo(props) {
	const fileChange = (info) => {
		console.log(info);
    analyseExcelToJson(info.file).then((res) => {
      console.log(res);
    });
	};

	const beforeUpload = (file) => {
	  console.log(file)
    analyseExcelToJson(file);
    return false;
  };

	useEffect(() => {
    getFileFromUrl('http://xxxxxxx.com/asdasd.xlsx', '导出文件.xlsx').then((file) => {
      analyseExcelToJson(file).then((res) => {
        console.log(res);
        return res;
      });
    });
  }, []);

	return (
		<div>

		</div>
	);
}

相关文档

xlsx库实现纯前端导入导出Excel