[Php] PHPExcel读取Excel文件(或来自客户端上传的)并返回二维数组

 客户端示例(antd - Upload组件): 文件上传

<div>
                    <Upload action='/api/login/upload' showUploadList={false}>
                        <Button>
                            <Icon type='upload' /> Upload
                        </Button>
                    </Upload>
                </div>

 php 接收客户端上传的接口(LoginController.php):

	public function upload()
	{
		$data = ExcelModule::readUploadedFile();
		if(!$data)
			return result(1, '接收excel文件失败, 具体请看日志');

		// todo: 针对读取到的二维数据进行相应处理

		return result(0, 'success', $data);     // 示例: 返回读取到的数据
	}

Php端依赖的接口:

/**
	 * 读取excel文件数据, 返回array数据
	 * @param $filePath
	 * @return array
	 */
	public static function readFile(string $filePath)
	{
		try {
			$reader = \PHPExcel_IOFactory::createReaderForFile($filePath);
			$excel = $reader->load($filePath);
			$sheet = $excel->getActiveSheet();

			return $sheet->toArray();
		}
		catch(\Exception $e)
		{
			log_message(sprintf('读取excel文件失败: file=%s, errorMsg=%s', $filePath, $e->getMessage()));
		}
	}

	/**
	 * 读取上传的Excel文件, 返回array数据
	 * @param string $name
	 * @return array
	 */
	public static function readUploadedFile(string $name = 'file')
	{
		$path = $_FILES[$name]['tmp_name'];

		return self::readFile($path);
	}

猜你喜欢

转载自www.cnblogs.com/joeblackzqq/p/13160492.html