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

导入文件的模板

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

如何设置浮动模式

最后打印的结果

相关推荐
Blossom.11818 小时前
大模型推理优化实战:连续批处理与PagedAttention性能提升300%
大数据·人工智能·python·神经网络·算法·机器学习·php
编程大师哥20 小时前
Boost C++
java·c++·php
fiveym1 天前
PXE启动菜单配置完全指南:打造高效网络装机入口
开发语言·网络·php
fiveym1 天前
PXE装机遇DHCP错误:ICMP echo reply导致IP分配失败原理解析
网络协议·tcp/ip·php
kaka-3331 天前
微信小程序中使用 xlsx(xlsx.mini.min.js)实现 Excel 导入导出功能
javascript·微信小程序·excel
开开心心_Every1 天前
优化C盘存储:自定义软件文档保存路径工具
java·网络·数据库·typescript·word·asp.net·excel
BingoGo1 天前
使用 PHP 和 WebSocket 构建实时聊天应用:完整指南
后端·php
JaguarJack1 天前
使用 PHP 和 WebSocket 构建实时聊天应用 完整指南
后端·php
狮子也疯狂1 天前
【天翼AI-星辰智能体平台】| 基于Excel表实现智能问数助手智能体开发实战
人工智能·oracle·excel
LCG米1 天前
基于LoRa的远距离低功耗农业传感器网络设计与实现(SX1278+STM32L071)
网络·stm32·php