zuixian113 2017-11-12 22:47:09 2650次浏览 0条回复 0 0 0

准备工作

1、excel表文件名为test20170919.xls,存放于当前项目目录下的.\upload\excel文件夹中; 1.png

2、利用PHPExcel组件读取excel表文件内容。 PS:PHPExcel组件使用详细内容可参考《Yii2-手动安装、引用第三方插件PHPExcel实例详解,Excel导出》,http://www.yiichina.com/topic/7142

3、写入的数据库表名为country。 PS:一次性添加多条数据至数据库详细说明可参考《使用createCommand()函数向数据库添加1条或多条数据》,http://www.yiichina.com/topic/7253 2.png

实例代码如下:

<?php namespace app\controllers; use Yii; use yii\web\Controller; use app\models\Country; use PHPExcel; class ImportController extends Controller {

public function actionImport()
{
    $basePath=Yii::$app->basePath;
    $file_url=$basePath.'\upload\excel\test20170919.xls';
    $filename=$file_url;
    $objPHPExcelnew=new PHPExcel();
    $objReader= \PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel=$objReader->load($filename);
    $sheet=$objPHPExcel->getActiveSheet();
    $highestRow=$sheet->getHighestRow();
    $highestColumn=$sheet->getHighestColumn();
    $highestColumnIndex=\PHPExcel_Cell::columnIndexFromString($highestColumn);
    $excelData=array();
    for($row=2;$row<=$highestRow;$row++)
    {
        for($col=0;$col<$highestColumnIndex;$col++)
        {
            $excelData[$row][]=(string)$sheet->getCellByColumnAndRow($col,$row)->getValue();
        }
    }
    Yii::$app->db->createCommand()->batchInsert('country', ['code', 'name','population'],$excelData)->execute();  
    echo 'insert success.';
}

}

    没有找到数据。
您需要登录后才可以回复。登录 | 立即注册