使用PHPExcel导入数据图片,在百度上找一下教程,所有文章都是以上的内容,不可用的,会报错,然后看了PHPExcel的文档有导入图片的案例,然后改动一下,保存图片后,把图片名整理到数组上,希望能帮到大家。
public function import ($basePath) {
$file = $basePath . '/database/data.xlsx'; //Excel File
$subDir = date('y') . '/' . date('m') . '/' . date('d') . '/'; //图片子目录存储
$imageFilePath = $basePath . '/users/product/'; //图片保存目录
if (!is_dir($imageFilePath . $subDir)) { //如果目录不存在,则创建
mkdir($imageFilePath . $subDir, 0777, true);
}
include $basePath . '/libraries/PHPExcel/PHPExcel.php'; //PHP Excel Libraries
$excelReader = new \PHPExcel_Reader_Excel2007();
$objPHPExcel = \PHPExcel_IOFactory::load($file);
$sheet = $objPHPExcel->getSheet(0);
//获取行数与列数,注意列数需要转换
$highestRowNum = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnNum = \PHPExcel_Cell::columnIndexFromString($highestColumn);
$titlefiled = array();
for ($i = 0; $i < $highestColumnNum; $i++) {
$cellName = \PHPExcel_Cell::stringFromColumnIndex($i) . '1';
$cellVal = $sheet->getCell($cellName)->getValue();//取得列内容
$titlefiled[] = $cellVal;
}
//开始取出数据并存入数组
$data = array();
for ($i = 2; $i <= $highestRowNum; $i++) {//ignore row 1
$row = array();
for ($j = 0; $j < $highestColumnNum; $j++) {
$cellName = \PHPExcel_Cell::stringFromColumnIndex($j) . $i;
$cellVal = $sheet->getCell($cellName)->getValue();
$row[$titlefiled[$j]] = $cellVal;
}
$data[] = $row;
}
/*取图片*/
foreach ($sheet->getDrawingCollection() as $drawing) {
if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
$extension = 'png';
break;
case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif';
break;
case \PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg';
break;
}
} else {
$zipReader = fopen($drawing->getPath(),'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader,1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
list($startColumn, $startRow) = \PHPExcel_Cell::coordinateFromString($drawing->getCoordinates()); //获取列与行号
$startColumnindex = \PHPExcel_Cell::columnIndexFromString($startColumn) - 1;
$name = $subDir . substr(time(), 5) . mt_rand(0, 9999) . '.' . $extension;
$data[$startRow - 2][$titlefiled[$startColumnindex]] = $name;
file_put_contents($imageFilePath . $name, $imageContents);
}
print_r($data);
}