具体代码:
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);
}
}