composer requirephpoffice/phpexcel:"*"
public function actionImport()
{
$model = new Quenstion();
$ok = "";
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, '字段名' ); //获取上传的文件实例
if ($file) {
$filename = date('Y-m-d',time()).'_'.rand(1,9999).".". $file->extension;
$file->saveAs($this->path.$filename); //保存文件
$format = $file->extension;
if(in_array($file->extension,array('xls','xlsx'))){
$excelFile = Yii::getAlias('@frontend/web/'$this->path.$filename.'');//获取文件名
// $phpexcel=new \PHPExcel();
// if ($format == "xls") {
// $excelReader = \PHPExcel_IOFactory::createReader('Excel5');
// } else {
// $excelReader = \PHPExcel_IOFactory::createReader('Excel2007');
// }
$fileType = \PHPExcel_IOFactory::identify($excelFile); //文件名自动判断文件类型
$excelReader = \PHPExcel_IOFactory::createReader($fileType);
$phpexcel = $excelReader->load($excelFile)->getSheet(0);//载入文件并获取第一个sheet
$total_line = $phpexcel->getHighestRow();//总行数
$total_column= $phpexcel->getHighestColumn();//总列数
// $highestColumn = $objWorksheet->getHighestColumn();//最大列数 为数字
// $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn); //将字母变为数字
if($total_line > 1){
for($row = 2;$row <= $total_line; $row++){
$data = array();
for($column = 'A'; $column <= $total_column; $column++){
$data[] = trim($phpexcel->getCell($column.$row)->getValue());
}
//一行行的插入数据库操作
$_model = new Quenstion;
$_model->content = $data[0];
$_model->create = time();
if ($_model->save()) {
$ok = 1;
}
}
}
if ($ok == 1){
$this->redirect(array('index']);
} else{
echo "<script>alert('操作失败');window.history.back();</script>";
}
}
}
} else {
return $this->render('import', [
'model' => $model,
]);
}
}