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,'操作成功');
    }

导入文件的模板

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

如何设置浮动模式

最后打印的结果

相关推荐
Qlittleboy2 小时前
tp5.0如何配置session保存到文件里,方便删除
缓存·php
葡萄城技术团队2 小时前
SpreadJS:让多源数据筛选排序如 Excel 般便捷高效
运维·服务器·excel
BingoGo2 小时前
PHP 性能优化实战 OPcache + FPM 极限优化配置
后端·php
Developer-YC3 小时前
像素图生成小程序开发全解析:从图片上传到Excel图纸
java·javascript·图像处理·微信小程序·excel
好多174 小时前
《Java中的IO流》
java·开发语言·php
小*-^-*九4 小时前
php 使用html 生成pdf word wkhtmltopdf 系列1
pdf·html·php
爱隐身的官人13 小时前
cfshow-web入门-php特性
python·php·ctf
懵逼的小黑子21 小时前
excel里面店铺这一列的数据结构是2C【uniteasone17】这种,我想只保留前面的2C部分,后面的【uniteasone17】不要
excel
leo__5201 天前
在Ubuntu 22.04系统中无需重启设置静态IP地址
tcp/ip·ubuntu·php