<form action="{:U('Index/files')}" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file"/> <br/> <input type="submit" name="submit" value="Submit"/> </form>
public function files(){ $filename = $_FILES['file']['name']; $ext = preg_split("/\./", $filename); $ext = strtolower($ext[1]); /* * 獲取文件後綴名 */ $allowed_types = array("xls", "xlsx"); $filePath = "./Public/excel/" . $_FILES["file"]["name"]; // print_r($filePath);die; if (!in_array($ext, $allowed_types)) { echo "File type is wrong!"; die; } // else if (file_exists($filePath)) { // echo "A file with this name already exists!"; // die; // } else { move_uploaded_file($_FILES["file"]["tmp_name"], $filePath); } /** * @param $val * @return string * 檢查文件名是否符合要求,若是符合,就保存到指定路徑。若是不符合,報錯。 */ // import("Org.Util.PHPExcel"); require_once "./ThinkPHP/Library/Org/Util/PHPExcel/Classes/PHPExcel.php"; //$filePath=$_FILES["file"]["tmp_name"]; //sleep(50); $PHPExcel = new \PHPExcel(); //默認用excel2007讀取excel,若格式不對,則用以前的版本進行讀取 $PHPReader = new \PHPExcel_Reader_Excel2007(); if (!$PHPReader->canRead($filePath)) { $PHPReader = new \PHPExcel_Reader_Excel5(); if (!$PHPReader->canRead($filePath)) { return $this->error(null, "no file"); } } $PHPExcel = $PHPReader->load($filePath); $sheetCount = $PHPExcel->getSheetCount(); $sheetNames = $PHPExcel->getSheetNames(); //var_dump($sheetNames); //die; /**讀取excel文件中有多少個sheet*/ $objExcel = array(); for ($SheetID = 0; $SheetID < $sheetCount; $SheetID++) { /**讀取excel文件中的工做表*/ $name = $sheetNames[$SheetID]; $currentSheet = $PHPExcel->getSheetByName($name); $name = iconv("utf-8", "gb2312", $name); /**取得最大的列號*/ $allColumn = $currentSheet->getHighestColumn(); /**取得一共有多少行*/ $allRow = $currentSheet->getHighestRow(); for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) { /**從第A列開始輸出*/ for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) { $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, $currentRow)->getValue(); $val = iconv("utf-8", "gb2312", $val); $objExcel[$name][$currentRow - 1][ord($currentColumn) - 65] = $val; //編碼須要轉換成gb2312 /* $val = urlencode($val); $objExcel[$name][$currentRow - 1][ord($currentColumn) - 65] = urldecode($val); */ } } } unlink($filePath); /* * $objExcel = json_encode($objExcel); * $objExcel = urldecode($objExcel); * 讀取文件中的內容,由於json_encode()的參數必須是utf-8編碼。爲了保證漢字輸出的結果,這裏先將數組中的內容用urlencode進行編碼, * 在被json_encode()編碼以後,再用urldecode解碼。 */ //return $objExcel; // print_r($objExcel); foreach ($objExcel as $k=>$v){ //取出裏面的id拼接成新的一維數組 $result = array_reduce($v, 'array_merge', array()); //過濾掉裏面的空值取出id $id = array_filter($result); } }