PHP上传带图片的excel 文件,后端读取内容,无法获取到图片。两种方式都获取不到图片数据
代码 1.
$file = $_FILES['file'];
// halt($file);
$reader = IOFactory::createReader('Xlsx');
// 打开文件 载入excel表格
$spreadsheet = $reader->load($file['tmp_name']);
$sheet = $spreadsheet->getActiveSheet();
// 获取内容的最大列 如:D
/* $highest = $sheet->getHighestColumn();*/
// 获取内容的最大行 如:4
$row = $sheet->getHighestRow();
// 遍历所有工作表
foreach ($spreadsheet->getAllSheets() as $sheet) {
// 获取当前工作表的所有绘图
$drawings = $sheet->getDrawingCollection();
// 遍历绘图对象
foreach ($drawings as $drawing) {
// 如果是图片,获取其路径和文件名
if ($drawing instanceof PHPExcel_Worksheet_Drawing) {
$imageFile = $drawing->getPath();
$imageFileName = $drawing->getIndexedFilename();
// 执行上传或处理图片的操作
// ...
}
}
}
代码2.
$imageFilePath = $_SERVER["DOCUMENT_ROOT"] . '/upload/image/material/'; //图片本地存储的路径
if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
mkdir($imageFilePath, 0777, true);
}
try {
/* $file = $_SERVER["ROOT_PATH"] . 'public/excel/2.xlsx';; //包含图片的Excel文件
$objRead = IOFactory::createReader('Xlsx');
$objSpreadsheet = $objRead->load($file);
$objWorksheet = $sheet->getSheetState();*/
$data = $sheet->toArray();
$img_data = [];// 图片数组
foreach ($sheet->getDrawingCollection() as $drawing) {
list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
$imageFileName = $drawing->getCoordinates() . mt_rand(1000, 9999);
switch ($drawing->getExtension()) {
case 'jpg':
case 'jpeg':
$imageFileName .= '.jpg';
$source = imagecreatefromjpeg($drawing->getPath());
imagejpeg($source, $imageFilePath . $imageFileName);
break;
case 'gif':
$imageFileName .= '.gif';
$source = imagecreatefromgif($drawing->getPath());
imagegif($source, $imageFilePath . $imageFileName);
break;
case 'png':
$imageFileName .= '.png';
$source = imagecreatefrompng($drawing->getPath());
imagepng($source, $imageFilePath . $imageFileName);
break;
}
$img_data[$startRow-1][$startColumn] = '/upload/image/material/' . $imageFileName;
}
// dump($img_data);
// 合并表格数据
if(!empty($img_data)){
foreach ($img_data as $key => $value){
//$data[$key][2] 是导入表格图片的哪一行
$data[$key][2] = $value['C'];
}
}
// dump($data);
} catch (\Exception $e) {
throw $e;
}