使用PHPEXCEL导入数据到数据库

导出功能参考:http://www.cnblogs.com/zhouqi666/p/5978017.html

比较严重的问题:当遇到excel数据量比较大的时候,会发生内存溢出的情况,目前无法解决

 

 

excel的数据格式为

 A     B

 

前面对应数据库type,后面对应电话号码

数据库

 

 

使用的是THINKPHP3.2.3其实就是连接数据库插入的时候用到和引用加载文件的时候用到TP只是了

代码如下

//引入PHPExcel 如果不是TP用require_once
vendor("PHPExcel.PHPExcel");
vendor("PHPExcel.IOFactory");
$cacheMethod = \PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( 'memoryCacheSize ' => '8MB');
\PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

// 实例化exel对象
//文件路径
$file_path = './Public/excel/test1.xlsx';

if (!file_exists($file_path)){
    die('file not exists');
}
//文件的扩展名
$ext = strtolower(pathinfo($file_path,PATHINFO_EXTENSION));
if ($ext == 'xlsx'){
    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
    $objPHPExcel = $objReader->load($file_path);
}elseif($ext == 'xls'){
    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load($file_path);
}
$objReader->setReadDataOnly(true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();//获取总行数
$highestColumn = $sheet->getHighestColumn();//获取总列数


//10  B
for ($i = 1;$i<=$highestRow;$i++){
    $record = array();//申明每条记录数组
    for ($j = 'A';$j<=$highestColumn;$j++){
        $record[] = $objPHPExcel->getActiveSheet()->getCell("$j$i")->getValue();//读取单元格
    }
    $record['type'] = $record[0];
    $record['phone'] = $record[1];
    $res = D('Test')->add($record);
    header("Content-type:text/html;charset=utf-8");
    if($res == false){
        echo '插入数据出错!数据格式为:';
        dump($record);
        die;
    }
}

 

posted @ 2017-06-09 18:31  周起  阅读(3761)  评论(0编辑  收藏  举报