柔晶美网络工作室

柔晶美网络工作室,倾心于web技术的博客站点

关注我 微信公众号

您现在的位置是: 首页 > 博客日记

laravel 导入含图片的excel表格

2021-01-05 admin laravel  1839

项目需要导入含图片(一个单元格可能多张图片)的excel表格,本来想用 Laravel/excel 这个包来做的,虽然方便,但是找了很多资料都没有写,就换成了phpspreadsheet。

安装:

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);
    }
}

文章评论


需要 登录 才能发表评论
热门评论
0条评论

暂时没有评论!