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

导入文件的模板

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

如何设置浮动模式

最后打印的结果

相关推荐
best_scenery10 小时前
excel绘制折线图
excel·分布图
大气层煮月亮10 小时前
Oracle EBS ERP开发——报表生成Excel标准模板设计
数据库·oracle·excel
偶尔贪玩的骑士17 小时前
Kioptrix Level 1渗透测试
linux·开发语言·网络安全·php
迎風吹頭髮17 小时前
Linux服务器编程实践58-getnameinfo函数:通过socket地址获取主机名与服务名
开发语言·数据库·php
探索宇宙真理.19 小时前
WordPress Flex QR Code Generator文件上传 | CVE-2025-10041 复现&研究
经验分享·php·安全漏洞
PFinal社区_南丞19 小时前
构建可维护的正则表达式系统-pfinal-regex-center设计与实现
后端·php
wearegogog12320 小时前
负荷聚类及其在MATLAB中的实现
matlab·php·聚类
BingoGo21 小时前
PHP 8.5 新特性 闭包可以作为常量表达式了
后端·php
葡萄城技术团队1 天前
从 Excel 到你的表格应用:保护工作表功能的嵌入实践指南
excel
JaguarJack1 天前
PHP 8.5 新特性 闭包可以作为常量表达式了
后端·php