TP3.2 phpexcel匯入excel
具體程式碼:
Vendor('PHPExcel.PHPExcel');
public function excel_runimport(){
$PHPExcel=new \PHPExcel();
if (! empty ( $_FILES ['file'] ['name'] )){
$file_types = explode ( ".", $_FILES ['file'] ['name'] );
$exts = $file_types [count ( $file_types ) - 1];
/*判別是不是.xls檔案,判別是不是excel檔案*/
if (strtolower ( $exts ) != "xlsx" || strtolower ( $exts ) != "xls"){
$this->error ( '不是Excel檔案,重新上傳');
}
//生成唯一的ID $filename = md5(uniqid(microtime(true),true));
$config=array( 'maxSize'=>70000000,
'exts'=>array('xlsx','xls'),
'rootPath'=>'./Uploads/excel/',
//儲存的檔名
'saveName' =>$filename,
//開啟子目錄
'subName' =>array('date','Ymd'),
);
$upload=new \Think\Upload($config);
$info=$upload->upload();
if($info){ if($exts == 'xls'){
import("Vendor.PHPExcel.Reader.Excel5");
$PHPReader=new \PHPExcel_Reader_Excel5();
}else if($exts == 'xlsx'){
import("Vendor.PHPExcel.Reader.Excel2007");
$PHPReader=new \PHPExcel_Reader_Excel2007();
}
$rootPath='./Uploads/excel/'; $savePath = $info['file']['savepath'];
$saveName=$info['file']['savename'];
//載入檔案建立物件
$filePath=$rootPath.$savePath.$saveName; $objReader = $PHPReader->load($filePath);
//獲取表中的第一個工作表,如果要獲取第二個,把0改為1,依次類推
$currentSheet=$objReader->getSheet(0);
//獲取總列數
$allColumn=$currentSheet->getHighestColumn();
//獲取總行數
$allRow=$currentSheet->getHighestRow();
//迴圈獲取表中的資料,$currentRow表示當前行,從哪行開始讀取資料,索引值從0開始
$data = array();//建立空陣列接收表格資料
//從第幾行開始迴圈
for($rowIndex=2;$rowIndex<=$allRow;$rowIndex++){
//迴圈讀取每個單元格的內容。注意行從1開始,列從A開始
//迴圈列
for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
$addr = $colIndex.$rowIndex;
$cell = $currentSheet->getCell($addr)->getValue();
if($cell instanceof PHPExcel_RichText){
//富文字轉換字串
$cell = $cell->__toString();
}
$data[$rowIndex][$colIndex] = $cell;
}
}
if(is_file($filename)) unlink($filename);
}else{
echo $upload->getError();
}
// $this->success ('匯入資料庫成功',U('excel_import'),1);
}
}