直接上代码:
<?php
/*加载PHPExcel的文件*/
require_once 'v1.7.6/Classes/PHPExcel.php';
require_once 'v1.7.6/Classes/PHPExcel/IOFactory.php';
require_once 'v1.7.6/Classes/PHPExcel/Reader/Excel5.php';
/*获取当前PHP文件的路径*/
$path =dirname(__FILE__);
/*获取上传的xlsx文件,并移动文件到指定路径(示例代码目标路径为$dest)*/
$fileName=$_FILES['myFile']['name'];
$dest = $path.'/uploadExcel/'.$fileName;
$res = move_uploaded_file($_FILES['myFile']['tmp_name'],$dest);
if($res)
{
/*excel 读取器*/
$objReader = PHPExcel_IOFactory::createReader('excel2007');
/*加载Excel文件*/
$objPHPExcel = $objReader->load('uploadExcel/'.$fileName,$encode='utf-8');
$drawing = new PHPExcel_Writer_Excel2007_Drawing();
$drawingHashTable = new PHPExcel_HashTable();
$drawingHashTable->addFromSource($drawing->allDrawings($objPHPExcel));
$sheet = $objPHPExcel->getSheet(0); // 默认只有一张sheet
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
/*此处作者需要一个独立的文件夹,可根据自己的需要调整*/
$dirName=date('Y-m-d-H-i-s');
$pathname=$path.'/';
$filedir='images/'.$dirName.'/';
if(!file_exists($pathname.$filedir)) {
mkdir($pathname.$filedir);
}
/*遍历单元格*/
for ($i = 0; $i < $drawingHashTable->count(); $i++)
{
$path =dirname(__FILE__);
$memoryDrawing = $drawingHashTable->getByIndex($i);
if ($memoryDrawing instanceof PHPExcel_Worksheet_Drawing)
{
$filename = $memoryDrawing->getPath();
/*此处的$filename打印出来为类似于zip://xxxxxxxxxxxxx.png的一个路径,作者也不知是个啥玩意*/
$imageFileName = $memoryDrawing->getIndexedFilename();
/*外网访问图片的路径*/
$path_f = 'http://x.x.x.x/DIRPATH/'.$filedir. $memoryDrawing->getIndexedFilename();
/*图片本地路径*/
$path = $pathname.$filedir.'/' . $memoryDrawing->getIndexedFilename();
/*自定义函数*/
copyfiles($filename, $path);
/*获取单元格的值*/
$cell = $memoryDrawing->getWorksheet()->getCell($memoryDrawing->getCoordinates());
/* 将该单元格的值设置为单元格的文本加上图片的 img 标签*/
$cell->setValue($cell->getValue() . '|||' . $path_f);
}
}
/*此时带有图片的单元格中的值变为:文本+|||+可访问的图片路径*/
}
function copyfiles($file1,$file2){
$contentx =@file_get_contents($file1);
$openedfile = fopen($file2, "w");
// http://www.manongjc.com/article/1350.html
fwrite($openedfile, $contentx);
fclose($openedfile);
if ($contentx === FALSE) {
$status=false;
}else $status=true;
return $status;
}
?>