[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);
	}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM