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

导入文件的模板

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

如何设置浮动模式

最后打印的结果

相关推荐
绵绵细雨中的乡音7 小时前
深入理解 ET 与 LT 模式及其在 Reactor 模型中的应用
服务器·网络·php
ServBay12 小时前
一个下午,一台电脑,终结你 90% 的 Symfony 重复劳动
后端·php·symfony
CodeKwang14 小时前
Qt实战:简易Excel表格 | 附完整源码
qt·excel·qtabwidget·qt控件
脸大是真的好~16 小时前
EasyExcel的使用
java·excel
kali-Myon18 小时前
2025春秋杯网络安全联赛冬季赛-day2
python·安全·web安全·ai·php·pwn·ctf
骆驼爱记录19 小时前
Word样式检查器使用指南
自动化·word·excel·wps·新人首发
IOsetting19 小时前
金山云主机添加开机路由
运维·服务器·开发语言·网络·php
kali-Myon19 小时前
2025春秋杯网络安全联赛冬季赛-day1
java·sql·安全·web安全·ai·php·web
kali-Myon19 小时前
2025春秋杯网络安全联赛冬季赛-day3
python·安全·web安全·ai·php·web·ctf
热爱生活的五柒20 小时前
wps office/word 表格左对齐后 文字前仍有空白,如何解决
excel