php excel批量导入,PHPExcel批量导入数据及图片

使用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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值