php 实现 导入excel 带图片导入

php 复制代码
    public function import(){
        $file = explode('.', $_FILES['file']['name']);
        if (!in_array(end($file), array('xls', 'xlsx', 'csv'))) {
            return $this->ajaxReturn($this->errorCode,'请选择xls文件');
        }
        $path = $_FILES['file']['tmp_name'];
        if (empty($path)) {
            return $this->ajaxReturn($this->errorCode,'文件上传失败');
        }

        set_time_limit(0);

        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
        $sheet = $spreadsheet->getActiveSheet(1);

        // 1. 收集图片
        $imgMap = []; // 行号 => [图片路径...]
        $saveDir = __DIR__ . '/uploads/excel/';
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0777, true);
        }
        $drawings = $sheet->getDrawingCollection();

        foreach ($sheet->getDrawingCollection() as $drawing) {
            $coordinate = $drawing->getCoordinates(); // e.g. B2
            preg_match('/([A-Z]+)(\d+)/', $coordinate, $matches);
            $col = $matches[1] ?? '';
            $rowIndex = $matches[2] ?? 0;

            $filename = uniqid('excel_');
            if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
                ob_start();
                call_user_func(
                    $drawing->getRenderingFunction(),
                    $drawing->getImageResource()
                );
                $imageContents = ob_get_contents();
                ob_end_clean();
                $extension = ($drawing->getMimeType() == \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG) ? 'png' : 'jpg';
                $fullpath = $saveDir . $filename . '.' . $extension;
                file_put_contents($fullpath, $imageContents);
            } else {
                $zipPath = $drawing->getPath();
                $extension = pathinfo($zipPath, PATHINFO_EXTENSION);
                $fullpath = $saveDir . $filename . '.' . $extension;
                copy($zipPath, $fullpath);
            }

            // 只存 B 列的图
            if ($col === 'B') {
                $imgMap[$rowIndex][] = '/uploads/excel/' . basename($fullpath);
            }
        }

        // 2. 读取表格数据
        $res = [];
        foreach ($sheet->getRowIterator(2) as $row) { // 从第2行开始,跳过表头
            $tmp = [];
            foreach ($row->getCellIterator() as $label => $cell) {
                $tmp[$label] = trim($cell->getFormattedValue());
            }
            if (filterEmptyArray($tmp)) {
                $res[$row->getRowIndex()] = $tmp;
            }
        }

        // 3. 拼接数据
        $list = [];
        foreach ($res as $rowIndex => $item) {
            $part_no   = $item['A'] ?? '';
            $part_name = $item['C'] ?? '';
            $car_model = $item['D'] ?? '';
            $brand     = $item['E'] ?? '';
            $stock     = (int)($item['F'] ?? 0);
            $price     = toPrice($item['G'] ?? 0);

            // 图片:B列,多张存 JSON
            $img = isset($imgMap[$rowIndex]) ? implode(',',$imgMap[$rowIndex]) : '';

            $list[] = [
                'part_no'    => $part_no,
                'part_name'  => $part_name,
                'car_model'  => $car_model,
                'brand'      => $brand,
                'stock'      => $stock,
                'price'      => $price,
                'img'        => $img,
                'partner_id' => $this->user_info['partner_id'],
                'subuser_id' => $this->user_info['subuser_id'],
            ];
        }
        dd($list);
        if (!empty($list)){
            Db::name('share')->insertAll($list);
        }

        return $this->ajaxReturn($this->successCode,'操作成功');
    }

导入文件的模板

一定要注意,图片一定要是浮动模式

如何设置浮动模式

最后打印的结果

相关推荐
christine-rr1 小时前
【25软考网工】第五章(11)【补充】网络互联设备
开发语言·网络·计算机网络·php·网络工程师·软考
linchare2 小时前
mac下homebrew安装的多个php版本如何切换?
php·homebrew·mac切换php版本
没有bug.的程序员3 小时前
分布式架构初识:为什么需要分布式
java·分布式·架构·php
瀚高PG实验室4 小时前
Navicat导入Excel至瀚高数据库
数据库·excel·瀚高数据库
半桔6 小时前
【网络编程】套接字入门:网络字节序与套接字种类剖析
linux·网络·php·套接字
铍镁钙锶钡镭8 小时前
FFmpeg 解封装简单流程
开发语言·ffmpeg·php
深蓝电商API1 天前
实战:爬取豆瓣电影Top250,并生成Excel榜单
爬虫·python·excel
未来之窗软件服务1 天前
万象EXCEL开发(八)excel公式解析与依赖映射 ——东方仙盟金丹期
前端·excel·仙盟创梦ide·东方仙盟·万象excel
王嘉俊9251 天前
ThinkPHP 入门:快速构建 PHP Web 应用的强大框架
开发语言·前端·后端·php·框架·thinkphp