用php把excel数据导入数据库

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了用php把excel数据导入数据库脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_360_4@PHPExcel是一个PHP类库,用来帮助我们简单、高效实现从Excel读取Excel的数据和导出数据到Excel。

先下载PHPExcel类库·

读取文件码:

<?PHP

header("content-tyPE:text/htML;charset=utf8");

include ‘./Classes/PHPExcel/IOFactory.PHP‘;//引入PHPExcel类

$inputFileName = ‘./test.xls‘;//读取的excel文件

date_default_timezone_set(PRC‘);

// 读取excel文件

try {

    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);

    $objReader = PHPExcel_IOFactory::createReader($inputFileType);

    $objPHPExcel = $objReader->load($inputFileName);

} catch(Exception $e) {

    die(‘加载文件发生错误:"‘.pathinfo($inputFileName,PATHINFO_BASENAME).‘": ‘.$e->getMessage());

}

$sheet = $objPHPExcel->getSheet(0);

$data=$sheet->toArray();//方法读取不到图片 图片需单独处理

$imageFilePath=‘./images/‘.date(‘Y-m-d‘).‘/‘;//图片在本地存储的路径

if (! file_exists ( $imageFilePath )) {

    mkdir("$imageFilePath",0777,true);

}

//处理图片

foreach($sheet->getDrawingCollection() as $img) {

    list($startColumn,$startRow)= PHPExcel_Cell::coordinateFromString($img->getCoordinates());//获取图片所在行和列

    $imageFileName = $img->getCoordinates() . mt_rand(100,999);

    swITch($img->getMimeType()) {

        case ‘image/jpg‘:

            $imageFileName.=‘.jpg‘;

            imagejpeg($img->getImageResource(),$imageFilePath.$imageFileName);

            break;

        case ‘image/gif‘:

            $imageFileName.=‘.gif‘;

            imagegif($img->getImageResource(),$imageFilePath.$imageFileName);

            break;

        case ‘image/png‘:

            $imageFileName.=‘.png‘;

            imagepng($img->getImageResource(),$imageFilePath.$imageFileName);

            break;

    }

    $startColumn = abc2decimal($startColumn);//由于图片所在位置的列号为字母,转化为数字

    $data[$startRow-1][$startColumn]=$imageFilePath.$imageFileName;//图片插入到数组中

 

}

print_r($data);die;

function ABC2decimal($abc){

    $ten = 0;

    $len = strlen($abc);

    for($i=1;$i<=$len;$i++){

        $char = substr($abc,0-$i,1);//反向获取单个字符

 

        $int = ord($char);

        $ten += ($int-65)*pow(26,$i-1);

    }

    return $ten;

}

以上代码只是处理图片,得到图片路径插入到数组中,如需数据入库,可循环insert,自行处理,打印结果如下:

用php把excel数据导入数据库

脚本宝典总结

以上是脚本宝典为你收集整理的用php把excel数据导入数据库全部内容,希望文章能够帮你解决用php把excel数据导入数据库所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。