PHPExcel数据导入(图文)

2025-12-25编程问答74408

phpexcel是一个php类库,用来帮助我们简单、高效实现从excel读取excel的数据和导出数据到excel。

相关视频课程:《PHP快速操控Excel之PhpSpreadsheet》

首先下载压缩包:

http://www.ufcn.cn/xiazai/leiku/1491

解压后如下:

在根目录创建一个test.php用来读取excel的内容 excel文件的内容如下:

酷宣AI

AI智能文章生成工具,支持输入主题生成高颜值带模板文章,适配多图场景,可一键同步多平台、导出多种格式,方便留存分享。

下载

然后test.php代码如下:

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

本文地址:https://www.ufcn.cn/article/2068140.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!