加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

用php把excel数据导入数据库

发布时间:2020-12-13 16:07:17 所属栏目:PHP教程 来源:网络整理
导读:PHPExcel是一个PHP类库,用来帮助我们简单、高效实现从Excel读取Excel的数据和导出数据到Excel。 先下载PHPExcel类库· 读取文件源码: ? php header ("content-type:text/html;charset=utf8" ); include ‘./Classes/PHPExcel/IOFactory.php‘; // 引入PHPE

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,自行处理,打印结果如下:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读