PhpSpreadsheet 导入图片功能

Excel
Laravel 4个月前 616 0

最近需要做个Excel 图片导入功能,本来是用 Laravel/excel 这个包来做的,虽然方便,但是找了很多资料都没有写,就换了一个包。

安装

composer require phpoffice/phpspreadsheet

使用

class Import{
private function getEnValue($zhName)
    {
        $column = [
            '名称' => 'name',
            '图片' => 'image',
        ];
        return $column[$zhName];
    }
public function import($file, int $sheet = 0, int $columnCnt = 0)
    {
        //设置图片路径
        $folder_name = "uploads/images/customers/" . date("Ym/d", time());
        if (!is_dir($folder_name)){
            mkdir($folder_name, 0775);
        }
        try {
            $objRead = IOFactory::createReader('Xlsx');
            $obj = $objRead->load($file);
            $currSheet = $obj->getSheet($sheet);
            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑,循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }
            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $titlefiled   = [];//excel 字段
            for($i = 1; $i <= $columnCnt; $i ++) {
                $cellName = Coordinate::stringFromColumnIndex($i) . '1';
                $cellVal = $currSheet->getCell($cellName)->getValue();
                $titlefiled[] = $this->getEnValue($cellVal);
            }
            $data = [];
            for($i = 2; $i <= $rowCnt; $i++) {
                $row = [];
                for($j = 1; $j <= $columnCnt; $j++) {
                    $cellName = Coordinate::stringFromColumnIndex($j) . $i;
                    $cellVal = $currSheet->getCell($cellName)->getValue();
                    $key = $titlefiled[$j-1];
                    $row[$key] = $cellVal;
                }
                $data[] = $row;
            }
            $temp = 0;//用于多张图片
            foreach ($currSheet->getDrawingCollection() as $drawing) {
                if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
                    ob_start();
                    call_user_func(
                        $drawing->getRenderingFunction(),
                        $drawing->getImageResource()
                    );
                    $imageContents = ob_get_contents();
                    ob_end_clean();
                    switch ($drawing->getMimeType()) {
                        case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
                            $extension = 'png';
                            break;
                        case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
                            $extension = 'gif';
                            break;
                        case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
                            $extension = 'jpg';
                            break;
                    }
                } else {
                    $zipReader = fopen($drawing->getPath(), 'r');
                    $imageContents = '';
                    while (!feof($zipReader)) {
                        $imageContents .= fread($zipReader, 1024);
                    }
                    fclose($zipReader);
                    $extension = $drawing->getExtension();
                }
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $startColumnindex = Coordinate::columnIndexFromString($startColumn) - 1;
                $myFileName = time() . '_' . str_random(10) . '.' . $extension;
                if ($temp == $startColumnindex) {
                    $file = "{$file},";
                    $file .= "{$folder_name}/{$myFileName}";
                    $data[$startRow - 2][$titlefiled[$startColumnindex]] = json_encode(explode(',', $file));
                } else {
                    $temp = $startColumnindex;
                    $file = "{$folder_name}/{$myFileName}";
                    $data[$startRow - 2][$titlefiled[$startColumnindex]] = json_encode($file);
                }
                file_put_contents("{$folder_name}/{$myFileName}", $imageContents);
            }
            return $data;
        }catch (\Exception $e) {
            throw $e;
        }
    }
}

控制器调用

use Import;

class ImportController extends Controller
{
    public funciton import(Request $request, Import $import) {
        $data = $import->import($request->file('file'));
        dd($data);
    }
}

原文: http://yiqiao.me/articles/18/phpspreadsheet-import-picture-function

版权声明: 自由转载-非商用-非衍生-保持署名 (创意共享3.0许可证)

同类文章