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,'操作成功');
}
导入文件的模板
一定要注意,图片一定要是浮动模式
如何设置浮动模式

最后打印的结果
