首先要有PHPExcel包。這個網上很好找到。
進入正題。
我寫了一個單獨的方法來供每個控制器試用。
上傳後讀取excel文件。
$info = $excels->move(ROOT_PATH . 'your path'); //上傳
$filename = 'your path'; //上傳後的路徑
$ext = $info->getExtension();
$excels = $this->importGet($filename,$ext,'path');
ImportGet函數
//$filename 文件路徑
//$exts 文件後綴
//$party 要保存的路徑(可自定義)
public function importGet($filename,$exts = 'xls',$party = null){
//導入PHPExcel類庫,因爲PHPExcel沒有用命名空間,只能inport導入
vendor("PHPExcel.PHPExcel");
//創建PHPExcel對象,注意,不能少了\
$PHPExcel = new \PHPExcel();
//如果excel文件後綴名爲.xls,導入這個類
if($exts == 'xls'){
vendor("PHPExcel.PHPExcel.Reader.Excel5");
$PHPReader = new \PHPExcel_Reader_Excel5();
}elseif($exts == 'xlsx'){
vendor("PHPExcel.PHPExcel.Reader.Excel2007");
$PHPReader = new \PHPExcel_Reader_Excel2007();
}
//載入文件
$PHPExcel = $PHPReader->load($filename);
//獲取表中的第一個工作表,如果要獲取第二個,把0改爲1,依次類推
$currentSheet = $PHPExcel->getSheet(0);
//獲取總列數
$allColumn = $currentSheet->getHighestColumn();
//獲取總行數
$allRow = $currentSheet->getHighestRow();
//該變量可判斷excel中是否有圖片
$allImage = $currentSheet->getDrawingCollection();
$data = array();
//圖片在本地存儲的路徑
$imageFilePath = 'your path';
if (! file_exists ( $imageFilePath )) {
mkdir("$imageFilePath", 0777, true);
}
//如果有圖片則進入循環
if($allImage){
foreach($allImage as $drawing){
//string 爲有圖片的表格座標 如 A2 B3等
$string = $drawing->getCoordinates();
//獲取excel中的圖片
$filename = $drawing->getPath();
$img = ‘your path’;
//這一句比較重要,將圖片放在路徑中
copy($filename, $img);
$cell = $currentSheet->getCell($string);
$path = 'http://quote.daowepark.com/' . $img;
//把圖片保存的路徑 丟回單元格,方便下面的保存。
$cell->setValue($path);
}
}
// 循環獲取表中的數據,
// $currentRow表示當前行,從哪行開始讀取數據,索引值從0開始
for($currentRow = 1;$currentRow <= $allRow;$currentRow++){
//從哪列開始,A表示第一列
for($currentColumn = 'A';$currentColumn <= $allColumn;$currentColumn++){
//數據座標
$address = $currentColumn . $currentRow;
//讀取到的數據,保存到數組$arr中
if($currentColumn === 'A'){
$data[$currentRow][$currentColumn] = (string)$currentSheet->getCell($address)->getValue();
}else{
$data[$currentRow][$currentColumn] =(string) $currentSheet->getCell($address)->getValue();
}
}
}
return $data;
}
題外話:
網上有很多調用了getMimeType()和getImageResource()等,但是我發現這兩個方法PHPExcel_Worksheet_Drawing類中是沒有的,是PHPExcel_Worksheet_MemoryDrawing類中的。在改寫了Drawing.php後不報錯了,讀取出來的對象中 imageResource依舊是空的,無奈只好嘗試copy這個方法。雖然成功了。但依舊不解。希望有朋友能夠解答。
共勉。