• PHPExcel数据导入(含图片)


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

    首先下载压缩包:

        https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8

    解压后如下:

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

    然后test.php代码如下:

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


  • 相关阅读:
    WPF 附件路由事件
    WPF 中的 路由事件
    WPF 中的DataTemplate 的嵌套
    wpf 的style
    C# 中的反射机制
    如何在github上fork以及同步原作者代码
    c# 执行python方法
    转载:c# 获取CPU温度(非WMI,直接读取硬件)
    C# 多个线程一直跑着While(true)
    C# TextBox控件 显示大量数据
  • 原文地址:https://www.cnblogs.com/changning0822/p/9921055.html
Copyright © 2020-2023  润新知